上篇文章说到了OkHttp Dispatcher对请求的调度管理,如果你看了上篇文章的话应该就知道了,okhttp请求是通过getResponseWithInterceptorChain()
方法来实现的。这篇文章就通过这个方法作为入口,来分析OkHttp的请求的过程,以及Interceptor的实现原理。如果没看过的话可以首先看下上一篇文章Dispatcher的调度过程分析
Interceptor是什么
官方的注释是这样写的:
Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls.
拦截器是一个强有力的,可以监视、重写、重试calls的工具
通过Interceptor你可以对Request和Response做任何事情,比如常见的统一设置Cookie,添加固定参数等待。关于拦截器的用法,这里就不在赘述,详细的可以参考官方wiki。这里默认你是知道怎么用的,如果不太明白的一定要去看下怎么使用。不然下面可能会懵逼的!
请求过程
所有的请求都是通过getResponseWithInterceptorChain()
方法完成的,下面看下这个方法中都干了什么。
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 (!forWebSocket) {
//用户添加的网络拦截器
interceptors.addAll(client.networkInterceptors());
}
//请求服务端
interceptors.add(new CallServerInterceptor(forWebSocket));
//第一个Chain
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
//通过链式请求的得到response
return chain.proceed(originalRequest);
}
上面的代码主要有三个疑问:
- 为什么通过
chain.proceed(originalRequest)
就可以得到被上面所有的拦截器处理过的Response? RetryAndFollowUpInterceptor
,BridgeInterceptor
,CacheInterceptor
,ConnectInterceptor
,CallServerInterceptor
这五个OkHttp自带的拦截器是干嘛的?- 添加了两次用户的拦截器分别是
client.interceptors()
,client.networkInterceptors()
,这两种拦截器有什么不同,添加的位置不同对他们的功能有什么影响?
1. chain.proceed(originalRequest)
做了什么
为了解决这个问题,首先看下Chain这个接口,以及它的实现类RealInterceptorChain是做什么的。
public interface Interceptor {
Response