用攔截器修改返回response,對特定的返回進(jìn)行修改操作
在開發(fā)的時候遇到這樣的需求:
小程序和ios已經(jīng)上線,Android端還在調(diào)接口,我用了retrofit把所有的參數(shù)統(tǒng)一處理,封裝了一個公共Bean類進(jìn)行擴(kuò)展,然后有一個接口在特定情況下無法解析json為公共bean類,這時候去修改bean和每個接口處理已經(jīng)來不及,這時候就可以用到攔截器了,攔截器可以攔截request,可以處理url,可以設(shè)置緩存,當(dāng)然也可以攔截response。
具體思路是:創(chuàng)建攔截器->根據(jù)chain獲取response->根據(jù)response判斷url是否需要特殊處理的->根據(jù)reponse.body().string()獲取json數(shù)據(jù)并轉(zhuǎn)換成bean類->修改bean類并創(chuàng)建新的responsebody和response->return修改完畢的response。
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;
}
其中有兩點(diǎn)需要特別注意一下:
1.ResponseBody的創(chuàng)建ResponseBody.create(MediaType.get("text/plain"), json);是用來根據(jù)json創(chuàng)建的MediaType.get("text/plain")是設(shè)置類型為text。
2.RequestBody調(diào)用string方法之后就不能用了,所以調(diào)用完了之后即便沒有修改也需要重新去創(chuàng)建ResponseBody和ResPonse,否則會報錯。
補(bǔ)充知識:攔截器中通過response返回JSON數(shù)據(jù)
做接口的攔截器時,需在攔截器中通過response返回接口是否允許調(diào)用的JSON信息:
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,對特定的返回進(jìn)行修改操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java基礎(chǔ)之邏輯運(yùn)算符知識總結(jié)
今天帶大家學(xué)習(xí)Java基礎(chǔ)知識,文中對Java邏輯運(yùn)算符進(jìn)行了非常詳細(xì)的介紹,有相關(guān)代碼示例,對正在學(xué)習(xí)java的小伙伴很有幫助,需要的朋友可以參考下2021-05-05
SpringBoot?整合mybatis+mybatis-plus的詳細(xì)步驟
這篇文章主要介紹了SpringBoot?整合mybatis+mybatis-plus的步驟,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
SpringBoot項目 文件上傳臨時目標(biāo)被刪除異常的處理方案
這篇文章主要介紹了SpringBoot項目 文件上傳臨時目標(biāo)被刪除異常的處理方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

