版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangshuaionline/article/details/89021265
承接上文:okhttp3简单实用及源码分析(一)
前文中理顺了okhttp3内部内部执行的步骤,每一步都做了什么,这一片文章我将继续通过源码的方式了解网络请求具体是怎么做的。
承接上文,具体的网络请求方法是在RealCall中调用getResponseWithInterceptorChain()方法:
这里我把源码进行了一下精简,方便分析
RealCall中:
Response getResponseWithInterceptorChain() throws IOException {
List<Interceptor> interceptors = new ArrayList<>();
//...默认是空的,暂时不分析
interceptors.add(new RetryAndFollowUpInterceptor(client));
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
//...默认是空的,暂时不分析
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, ..., ..., 0,
..., this,...,..., ...);
...
try {
//执行网络请求的跳转节点
Response response = chain.proceed(originalRequest);
...
return response;
} catch (IOException e) {
...
} finally {
...
}
}
RealInterceptorChain中:
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
throws IOException {
...
RealInterceptorChain next = new RealInterceptorChain(interceptors, ..., ...,
index + 1, ..., call, ..., ..., ...);
Interceptor interceptor = interceptors.get(index);
//执行网络请求的跳转节点
Response response = interceptor.intercept(next);
...
return response;
}
由于index传过来的是0,那么关联到RetryAndFollowUpInterceptor中:
@Override public Response intercept(Chain chain) throws IOException {
...
while (true) {
...
try {
//执行网络请求的跳转节点
response = realChain.proceed(request, transmitter, null);
...
} catch (RouteException e) {
...
continue;
}finally {
...
}
...
if (...) {
...
return response;
}
...
}
}
这里有没有很眼熟?是的,会自动调用List的下一个Interceptor【设计模式之责任链模式】那么我们分析每一个拦截器便会了解okhttp3内部到底都做了什么:工厂方法模式
1. RetryAndFollowUpInterceptor
功能:网络故障时候重试并跟进的拦截器。
2. BridgeInterceptor
功能:添加请求头。
3. CacheInterceptor
功能:请求缓存策略。缓存使用DiskLruCache以及CacheStrategy.Factory进行管理。
4. ConnectInterceptor
功能:负责重定向。
5. CallServerInterceptor
功能:网络请求。