okhttp中多个拦截器前一个拦截后,后面的拦截器是否不拦截
我在使用okhttp3时设置拦截器时发现一个问题就是在当中设置多个拦截器
//打印log的拦截器
client.addInterceptor(LoggingInterceptor);
//HTTP检查器
client.addInterceptor(new ChuckInterceptor(application));
//检查是否有网络
client.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR);
//无网络读取本地缓存
client.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR);
我在第三个中打印log发现没有log打印出来,只有第一个拦截器中有log打印,所以我想问下是否时okhttp中的拦截器会当前拦截会导致之后的拦截器无法拦截
//判断是否需要读取缓存
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
boolean netWorkConection = NetUtils.hasNetWorkConection(MyApplication.getIntstance());
Request request = chain.request();
if (!netWorkConection) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (netWorkConection) {
//有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
String cacheControl = request.cacheControl().toString();
response.newBuilder()
.removeHeader("Pragma")// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.header("Cache-Control", cacheControl)
.build();
} else {
int maxStale = 60 * 60 * 24 * 7;
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
KLog.i(TAG, "-----LoggingInterceptor----- :\nrequest url:" + request.url() + "\nbody:" + response.body().string() + "\n");
return response;
}
};
//打印log的拦截器
private static final Interceptor LoggingInterceptor = new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
okhttp3.Response response = chain.proceed(chain.request());
long t2 = System.nanoTime();
okhttp3.MediaType mediaType = response.body().contentType();
String content = response.body().string();
KLog.i(TAG, "-----LoggingInterceptor----- :\nrequest url:" + request.url() + "\ntime:" + (t2 - t1) / 1e6d + "\nbody:" + content + "\n");
return response.newBuilder()
.body(okhttp3.ResponseBody.create(mediaType, content))
.build();
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
response.body().string() 只能调用一次