基本思路:
1、在拦截器中获取接口返回的数据
2、修改返回的数据
3、将新的数据放入Response中(需要重新创建Response)
image.png
public class ResponseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
// 在拦截器中获取接口返回的数据
Request originalRequest = chain.request();
Response response = chain.proceed(originalRequest);
byte[] respBytes = response.body().bytes();
String respString = new String(respBytes);
// 修改返回的数据
try {
JSONObject object = new JSONObject(respString);
object.put("new_key", "新的数据");
respBytes = object.toString().getBytes(StandardCharsets.UTF_8);
} catch (Exception ex) {
ex.printStackTrace();
}
// 将新的数据放入Response中
MediaType mediaType = response.body().contentType();
return response.newBuilder().body(ResponseBody.create(mediaType, respBytes)).build();
}
}