承接上文: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
功能:網絡請求。