之前第二部分的时候留下一块东西没有解决,就是Interceptor部分,这两天大概看了一下,做一下大致的整理吧。
OkHttp框架里面对应用层相关的协议封装的真的是很好,以至于我看着看着发现看到什么代理啊路由啊TLS信息啊什么的,感觉这些实在是深入不下去了。如果以后真的要深入用到OkHttp且需要关系到这些的时候再来看好了。
Interceptor
中文解释是拦截器,它所实现的功能,就是对request和response拦截,进行相应的修改和处理之后得到我们更想要得到的结果。例如之前(二)里面看到的retryAndFollowUpInterceptor,就是一个重定向拦截器,当得到一个网络响应之后,通过判断responseCode来决定是否需要重定向到新的URL,自动发送新的HTTP请求,这样就免去了我们自己去进行这一部分的操作。另外,如果我们要增加缓存操作,也可以通过Interceptor来实现,如果缓存中存有对应请求的内容,就直接返回缓存中的response,反之在进行网络请求。我们也可以自定义Interceptor来实现自己想要的操作。不得不说这个设计真的很强。
流程图
首先先看一下上一篇提到过一个RealCall中用于网络请求的源码:
private Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!retryAndFollowUpInterceptor.isForWebSocket()) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(
retryAndFollowUpInterceptor.isForWebSocket()));
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
这部分的chain.proceed()处理流程大致如下,箭头表示整个数据处理的走向:
在我看来有点像是一个栈,在处理request的时候interceptor依次入栈,然后出处理respons