攔截器是OkHttp中提供的一種強大機制,它能夠實現網絡監聽、請求以及響應重寫、請求失敗重試等功能。緩存
如上圖所示,這就OkHttp內部提供給咱們的攔截器,就是當咱們發起一個http請求的時候,OkHttp就會經過這個攔截器鏈來執行http請求。其中包括:bash
BridgeInterceptor和 CacheInterceptor 主要是用來補充用戶請求建立當中缺乏的一些必需的http請求頭和處理緩存的功能。cookie
ConnectInterceptor 主要是負責創建可用的連接,CallServerInterceptor 主要是負責將http請求寫進網絡的IO流當中,而且從網絡IO流當中讀取服務端返回給客戶端的數據。網絡
上篇文章 OkHttpClient源碼分析(一)——同步、異步請求的執行流程和源碼分析 有說起到一個很重要的方法getResponseWithInterceptorChain(),同步請求的話,是在RealCall類中的excute()方法中調用到該方法,而異步請求是在RealCall的內部類AsyncCal中的excute()方法中調用,查看該方法的源碼:異步
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));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
}
複製代碼
1、方法裏初始化了一個Interceptor的集合,添加了OkHttpClient中配置的攔截器集合,而後依次添加了上述說起到的那五個攔截器;ide
2、建立一個攔截器鏈RealInterceptorChain,並執行攔截器鏈的proceed()方法;源碼分析
查看RealInterceptorChain類的proceed()方法:post
public Response proceed(Request request, StreamAllocation streamAllocation, HttpStream httpStream,
Connection connection) throws IOException {
...
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpStream, connection, index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
...
}
複製代碼
其中,核心的代碼就在這裏,這裏再次建立了RealInterceptorChain對象,此時建立的是下一個攔截器鏈,傳入的是index + 1,並經過調用當前Interceptor的intercept()方法,將下一個攔截器鏈傳入,獲得Response對象,至於攔截器的intercept()方法,下面將會分析。ui
主要做用是負責網絡請求失敗重連,須要注意的是,並非全部的網絡請求失敗之後均可以進行重連,它是有必定的限制範圍的,OkHttp內部會幫咱們檢測網絡異常和響應碼的判斷,若是都在它的限制範圍內的話,就會進行網絡重連。this
源碼主要看intercept()方法:
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()));
int followUpCount = 0;
Response priorResponse = null;
...
}
複製代碼
這裏建立了一個StreamAllocation對象,StreamAllocation對象是用來創建執行Http請求所須要的網絡組件的,從它名字能夠看出,它是用來分配stream的,主要是用於獲取鏈接服務端的connection和用於與服務端進行數據傳輸的輸入輸出流 。
詳細的邏輯都在intercept()方法中的while循環中,這裏不作詳細介紹,主要是介紹其中的這個:
while (true) {
...
try {
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
}
...
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
...
}
複製代碼
這裏咱們能夠發現,RealInterceptorChain調用proceed()方法,方法裏又建立了一個RealInterceptorChain對象(下一個攔截器鏈 index + 1),而後經過index獲取到當前執行到的攔截器,調用攔截器的intercept()方法,這裏intercept()方法中,再次調用了RealInterceptorChain的proceed()方法,造成了遞歸。
以上代碼是對重試的次數進行判斷,由此可知,並非無限次的進行網絡重試,而是有必定的重試次數的,MAX_FOLLOW_UPS 是一個常量,值爲20,也就是說最多進行20次重試,若是還不成功的話,就會釋放StreamAllocation對象和拋出ProtocolException異常。
總結:
一樣也是看核心方法intercept():
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
...
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
...
Response networkResponse = chain.proceed(requestBuilder.build());
...
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
複製代碼
這裏並無貼上整個方法的代碼,省略了部分,主要的操做就是爲發起的Request請求添加請求頭信息,其中一樣也調用了proceed()方法遞歸調用下個攔截器,最後面是針對通過gzip壓縮過的Response進行解壓處理,這裏經過判斷是否支持gzip壓縮且請求頭裏面的"Content-Encoding"的value是不是"gzip"來判斷是否須要進行gzip解壓。
總結:
下一篇將爲你們介紹OkHttp的緩存機制,感興趣的朋友能夠繼續閱讀: