Okhttp拦截器中修改返回的数据

基本思路:
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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容