用拦截器修改返回response,对特定的返回进行修改操作

2025-05-29 0 99

在开发的时候遇到这样的需求:

小程序和ios已经上线,Android端还在调接口,我用了retrofit把所有的参数统一处理,封装了一个公共Bean类进行扩展,然后有一个接口在特定情况下无法解析json为公共bean类,这时候去修改bean和每个接口处理已经来不及,这时候就可以用到拦截器了,拦截器可以拦截request,可以处理url,可以设置缓存,当然也可以拦截response。

具体思路是:创建拦截器->根据chain获取response->根据response判断url是否需要特殊处理的->根据reponse.body().string()获取json数据并转换成bean类->修改bean类并创建新的responsebody和response->return修改完毕的response。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
public Interceptor getSignInInterceptor(){

Interceptor interceptor = new Interceptor() {

@Override

public Response intercept(Chain chain) throws IOException {

Request request = chain.request();

Response response = chain.proceed(request);

if(request.url().toString().contains(URL)) {

String json =response.body().string();

HttpResult<Object> responseResult = JsonUtil.parseJsonToBean(json,HttpResult.class);

if(responseResult.getCode() == 1508) {

responseResult.setData(null);

String responseJson = JsonUtil.parseObjToJson(responseResult);

ResponseBody myBody = ResponseBody.create(MediaType.get("text/plain"), responseJson);

return response.newBuilder().body(myBody).build();

}

ResponseBody myBody = ResponseBody.create(MediaType.get("text/plain"), json);

return response.newBuilder().body(myBody).build();

}

return response;

}

};

return interceptor;

}

其中有两点需要特别注意一下:

1.ResponseBody的创建ResponseBody.create(MediaType.get("text/plain"), json);是用来根据json创建的MediaType.get("text/plain")是设置类型为text。

2.RequestBody调用string方法之后就不能用了,所以调用完了之后即便没有修改也需要重新去创建ResponseBody和ResPonse,否则会报错。

补充知识:拦截器中通过response返回JSON数据

做接口的拦截器时,需在拦截器中通过response返回接口是否允许调用的JSON信息:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
response.setCharacterEncoding( "UTF-8");

response.setContentType( "application/json; charset=utf-8");

PrintWriter out = null ;

try{

JSONObject res = new JSONObject();

res.put( "success", "false");

res.put( "msg", "xxxx");

out = response.getWriter();

out.append(res.toString());

return false;

}

catch (Excepton e){

e.printStackTrace();

response.sendError( 500);

return false;

}

以上这篇用拦截器修改返回response,对特定的返回进行修改操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/a__sen/article/details/101536914

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 用拦截器修改返回response,对特定的返回进行修改操作 https://www.kuaiidc.com/116504.html

相关文章

发表评论
暂无评论