OKHTTP3添加一个拦截器,碰到接口只返回code200的接口,添加一个NullResponseInterceptor拦截器,再次封装Response数据
okhttp初始化处添加拦截器
okhttpBuilder.addInterceptor(new NullResponseInterceptor());
拦截器NullResponseInterceptor的代码
/**
* Created by dexter on 2019-09-09.
* Retrofit2的2.0版本不支持解析OnNext的Null数据,拦截器做规范化返回数据
*/
public class NullResponseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (response.body().contentLength() == 0 && response.code() == 200) {
MediaType mediaType = response.body().contentType();
//*********添加自定义的解析基类*********
BaseJson baseJson = new BaseJson();
baseJson.code = 200;
baseJson.message = "Success";
//*********添加自定义的解析基类*********
String baseJsonString = new Gson().toJson(baseJson);
ResponseBody responseBody = ResponseBody.create(mediaType, baseJsonString);
return response.newBuilder().body(responseBody).build();
} else {
return response;
}
}
}
网友评论