本文中源碼基于OkHttp 3.6.0
- 《OkHttp Request 請求執(zhí)行流程》
- 《OkHttp - Interceptors(一)》
- 《OkHttp - Interceptors(二)》
- 《OkHttp - Interceptors(三)》
- 《OkHttp - Interceptors(四)》
上一篇文章《OkHttp Request 請求執(zhí)行流程》中分析我們知道 OkHttp 的請求是一個鏈式的過程,在 RealCall 的 getResponseWithInterceptorChain() 方法中構建了一個請求處理鏈,鏈上的每一個節(jié)點都有相對獨立的功能,當它們完成自己的請求任務后就把處理結果返回給上一個節(jié)點,直到最后返回給發(fā)起請求的用戶。這些處理請求的節(jié)點就是 Interceptor,它們由下面幾種類型構成:
- 自定義 Interceptors ,由用戶自定義的 Interceptor,最早接收到 Request、最后完成對 Response 的處理;
- RetryAndFollowupInterceptor,負責處理鏈接失敗時的重試及重定向請求;
- BridgeInterceptor, 負責處理請求的 headers、cookie、gzip;
- CacheInterceptor,負責匹配請求的緩存、驗證緩存有效性、及保存響應的緩存;
- ConnectInterceptor,負責創(chuàng)建到服務器的鏈接;
- 自定義 Network Interceptors,同樣由用戶自定義,與之前的 Interceptor 最大的區(qū)別就是,請求執(zhí)行到這里已經與服務器建立上了連接;
- CallServerInterceptor,對服務器發(fā)起實際的請求,接收返回結果。
下面我們按照順序依次來分析各個系統(tǒng) Interceptor 對請求的處理。
- RetryAndFollowupInterceptor
RetryAndFollowupInterceptor 是第一個接收到 Request 的系統(tǒng) Interceptor ,它的主要作用是在后續(xù) Interceptor 處理請求遇到錯誤時,重新構造一個新的 Request 并再次發(fā)起請求,下面我們來看看它的 intercept 方法。
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 構建一個 StreamAllocation,其提供建立連接、管理復用連接的能力
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
// 重定向次數計數器,默認超過20次就直接拋出錯誤
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response = null;
boolean releaseConnection = true;
try {
// 交給下一個 Interceptor 處理請求
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
// 連接失敗,判斷是否可以恢復連接,若不可恢復,直接拋出異常結束請求。此時還沒有發(fā)送請求
if (!recover(e.getLastConnectException(), false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
continue;
} catch (IOException e) {
// 在與服務器的通信過程中發(fā)生錯誤,判斷是否可以恢復連接,此時可能已經向服務器發(fā)送了請求
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// 其他異常不處理,關閉連接釋放資源。
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
// 根據服務器返回響應構造一個新的 Request
Request followUp = followUpRequest(response);
// 如果不支持重試,直接返回服務器結果
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
closeQuietly(response.body());
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
// 如果不能復用一條連接,需要使用新的地址重新構建一個連接
if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(followUp.url()), callStackTrace);
} else if (streamAllocation.codec() != null) {
throw new IllegalStateException("Closing the body of " + response
+ " didn't close its backing stream. Bad interceptor?");
}
request = followUp;
priorResponse = response;
}
}
在將請求交由下一個節(jié)點處理之前,RetryAndFollowupInterceptor 創(chuàng)建了一個 StreamAllocation ,這個對象用來創(chuàng)建并維護客戶端到服務器的鏈接,在分析 ConnectInterceptor 的時候我們再來詳細地講解其功能實現。
在請求執(zhí)行的過程中,由于網絡等原因,可能會出現與服務器鏈接失敗、數據傳輸失敗等情況,為了盡量保證請求的可靠性,OkHttp 會自動對失敗的請求進行重試。這時通過 recover() 判斷客戶端是否可以恢復與服務器的連接,如果可以恢復,那么會使用 StreamAllocation 選擇另外一個 Route 重新創(chuàng)建一個連接;如果不能恢復則只能關閉連接,拋出異常。
private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
streamAllocation.streamFailed(e);
// 如果在 OkHttpClient 中設置了retryOnConnectionFailure,表示我們不允許進行請求重試
if (!client.retryOnConnectionFailure()) return false;
// 如果請求中包含不能重復提交的內容,則不允許重試
if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;
// 根據錯誤類型判斷是否能夠重試
if (!isRecoverable(e, requestSendStarted)) return false;
// 連接中并不存在下一個路由地址,則不能重試
if (!streamAllocation.hasMoreRoutes()) return false;
// For failure recovery, use the same route selector with a new connection.
return true;
}
在我們正常連接到服務器并發(fā)起請求的情況下,服務器返回的 Response 任然有可能不是我們需要的結果,比如發(fā)生服務器需要身份認證(401)、重定向(30x)的時候。那么下面我們再來看看 OkHttp 中對這一部分邏輯的處理。
private Request followUpRequest(Response userResponse) throws IOException {
if (userResponse == null) throw new IllegalStateException();
Connection connection = streamAllocation.connection();
Route route = connection != null
? connection.route()
: null;
int responseCode = userResponse.code();
final String method = userResponse.request().method();
switch (responseCode) {
// 407,代理認證,表示需要經過代理服務器的授權
case HTTP_PROXY_AUTH:
Proxy selectedProxy = route != null
? route.proxy()
: client.proxy();
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
}
// 交由 OkHttpClient 中設置的代理認證處理,默認未設置
return client.proxyAuthenticator().authenticate(route, userResponse);
// 401,基本認證,訪問被拒絕,需要授權
case HTTP_UNAUTHORIZED:
// 交由用戶設置的認證處理,默認未設置
return client.authenticator().authenticate(route, userResponse);
// 308,永久遷移
case HTTP_PERM_REDIRECT:
// 307,臨時遷移
case HTTP_TEMP_REDIRECT:
// 服務器為了禁止一味地使用重定向,將這幾個狀態(tài)碼區(qū)分開,如果該請求不是 GET 或者 HEAD,那么不進行自動重定向,交給用戶自己處理
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// 300,請求的資源存在多個候選地址,同時返回一個選項列表
case HTTP_MULT_CHOICE:
// 301,資源被移動到新的位置
case HTTP_MOVED_PERM:
// 302,類似301
case HTTP_MOVED_TEMP:
// 303,類似301、302
case HTTP_SEE_OTHER:
// 如果設置禁止重定向,則返回 null
if (!client.followRedirects()) return null;
String location = userResponse.header("Location");
if (location == null) return null;
// 解析 Location 中地址
HttpUrl url = userResponse.request().url().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null) return null;
// 這里判斷原始請求地址和重定向的地址是否使用相同協(xié)議(同為 Http 或 Https)
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
// 判斷 OkHttp 中配置是否允許跨協(xié)議的重定向
if (!sameScheme && !client.followSslRedirects()) return null;
// Most redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder();
// 這里處理重定向請求中的實體部分
if (HttpMethod.permitsRequestBody(method)) {
// 重定向中是否允許攜帶實體(PROPFIND方法允許攜帶實體,其他方法不允許攜帶實體,需要將請求改為 GET 請求)
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
requestBuilder.method(method, requestBody);
}
if (!maintainBody) {
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
}
// When redirecting across hosts, drop all authentication headers. This
// is potentially annoying to the application layer since they have no
// way to retain them.
if (!sameConnection(userResponse, url)) {
requestBuilder.removeHeader("Authorization");
}
// 使用重定向指定地址構建一個新的 request
return requestBuilder.url(url).build();
// 408,請求超時,不修改請求,直接重試
case HTTP_CLIENT_TIMEOUT:
// 408's are rare in practice, but some servers like HAProxy use this response code. The
// spec says that we may repeat the request without modifications. Modern browsers also
// repeat the request (even non-idempotent ones.)
if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}
return userResponse.request();
default:
return null;
}
}
RetryAndFollowupInterceptor 在接收到來自服務器的 Response 后,通過 followUpRequest() 方法判斷是否需要對該請求進行重試,如果需要重試,則構建一個新的 Request 以便再次發(fā)起請求;如果拿到的 Response 就是最終的結果,就直接將 Response 返回給用戶,完成請求。

- BridgeInterceptor
BridgeInterceptor 中的源碼理解起來相對比較簡單,在將請求交付給下一個處理節(jié)點前,它的主要作用是在 Request 的 Header 中添加缺失的頭部信息(Content-Type、本地存儲的 Cookie 信息),以及在接收到服務器返回的 Response 后存儲 Header 中的 Cookie,并解壓響應實體(如果是 gzip 的話)。
public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
// 設置 Content-Type(text、image、video 等)
requestBuilder.header("Content-Type", contentType.toString());
}
// contentLength 用于標識實體實體大小,便于服務器判斷實體是否傳輸完畢。
// 如果指定了 contentLength,則在 header 中添加;如果沒有指定,則使用 Transfer-Encoding: chunked 分塊編碼方式。
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
// 設置 Host
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
// 請求保持連接
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
// 獲取對應 url 下的 cookie
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
// 后續(xù) Interceptor 處理請求
Response networkResponse = chain.proceed(requestBuilder.build());
// 保持 Response 中的 cookie
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
// 如果請求中設置了 Content-Encoding: gzip,完成對 body 的解壓
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);
responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}