下面先給出一張圖,其中包含了OkHttp實現的默認攔截器,也是我們今天要分析的。
文章目錄
簡單示例引入
在開始我們今天的主題之前,我們還是以一個簡單的例子引入,下面還是我們的老例子,執行一個簡單Http請求。
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
try (Response response = call.execute()) {
return response.body().string();
}
}
RealCall的execute同步請求。
RealCall中的AsyncCall的execute異步請求。
它們都執行了Response response = getResponseWithInterceptorChain();
。
下面是該方法的代碼:
這裏主要是創建了一個Interceptor列表,然後創建一個Interceptor.Chain對象來處理請求並最終獲取響應,那我再跟蹤一下該RealInterceptorChain對象。
下面是該對象中最重要的方法,也就是處理請求的方法。(proceed方法)
這裏有一個非常重要的類StreamAllocation*(由於後面涉及zhge類比較多,這裏先簡單介紹一下,後面的文章會單獨分析):
我們要明白HTTP通信執行網絡"請求"需要在"連接"上建立一個新的"流",我們將StreamAllocation稱之流的橋樑,它負責爲一次"請求"尋找"連接"並建立"流",從而完成遠程通信。所以說StreamAllocation與"請求"、“連接”、"流"都有關。
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
// If we already have a stream, confirm that the incoming request will use it.
if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must retain the same host and port");
}
// If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
// Confirm that the intercepted response isn't null.
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
if (response.body() == null) {
throw new IllegalStateException(
"interceptor " + interceptor + " returned a response with no body");
}
return response;
}
在RealInterceptorChain.proceed()中,除了對狀態及獲取的reponse做檢查之外,最主要的事情即是構造新的RealInterceptorChain對象,獲取對應Interceptor,並調用Interceptor的intercept(next)了。在這裏,index充當迭代器或指示器的角色,用於指出當前正在處理的Interceptor。
RealInterceptorChain + Interceptor實現了裝飾器模式,實現了請求/響應的串式或流式處理。
接下來我們通過debug的方式展示的攔截器如下圖所示.
即
- RetryAndFollowUpInterceptor
- BridgeInterceptor
- CacheInterceptor
- ConnectInterceptor
- CallServerInterceptor
通過debug的方式得到OkHttp中Http請求的執行流程入下圖所示:
接下來一一揭曉:
RetryAndFollowUpInterceptor
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
/** todo:
RetryAndFollowUpInterceptor在intercept()中首先從client取得connection pool,用所請求的URL創建Address對象,並以此創建StreamAllocation對象。
**/
//Address描述某一個特定的服務器地址。
StreamAllocation對象則用於分配一個到特定的服務器地址的流HttpStream,
這個HttpStream可能是從connection pool中取得的之前沒有釋放的連接,
也可能是重新分配的。RetryAndFollowUpInterceptor
這裏算是爲後面的操作準備執行條件StreamAllocation。
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//隨後RetryAndFollowUpInterceptor.intercept()利用Interceptor鏈中
後面的Interceptor來獲取網絡響應。並檢查是否爲重定向響應。
若不是就將響應返回,若是則做進一步處理
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
} finally {
// We're throwing an unchecked exception. Release any resources.
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();
}
//對於重定向的響應,RetryAndFollowUpInterceptor.intercept()
會利用響應的信息創建一個新的請求。
並檢查新請求的服務器地址與老地址是否相同,
若不相同則會根據新的地址創建Address對象及StreamAllocation對象。
Request followUp = followUpRequest(response);
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
closeQuietly(response.body());
//RetryAndFollowUpInterceptor對重定向的響應也不會無休止的處理下去,
它處理的最多的重定向級數爲20次,超過20次時,它會拋異常出來。
//MAX_FOLLOW_UPS = 20
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()), call, eventListener, 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;
}
}
OkHttp提供了非常好的容錯機制,可以從某些類型的網絡錯誤中恢復,即出錯重試機制。這種出錯重試機制主要由recover()來實現,主要是對某些類型IOException的恢復,恢復的次數會由StreamAllocation控制。
總結一下RetryAndFollowUpInterceptor做的事情:
- 創建StreamAllocation對象,爲後面流程的執行準備條件
- 處理重定向的HTTP響應
- 錯誤恢復
BridgeInterceptor
在執行完RetryAndFollowUpInterceptor之後,執行我們的BridgeInterceptor。
這個Interceptor做的事情相對比較簡單,可以分爲發送請求之前和收到響應之後兩個階段來看。
首先我們先看一下發送請求之前的代碼:
在發送請求階段,BridgeInterceptor補全一些http header,這主要包括Content-Type、Content-Length、Transfer-Encoding、Host、Connection、Accept-Encoding、User-Agent,還加載Cookie,隨後創建新的Request,並交給後續的Interceptor處理,以獲取響應。
@Override 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) {
requestBuilder.header("Content-Type", contentType.toString());
}
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");
}
}
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");
}
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());
}
Response networkResponse = chain.proceed(requestBuilder.build());
下面是收到響應之後的代碼:
而在從後續的Interceptor獲取響應之後,會首先保存Cookie。如果服務器返回的響應的content是以gzip壓縮過的,則會先進行解壓縮,移除響應中的header Content-Encoding和Content-Length,構造新的響應並返回;否則直接返回響應。
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
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();
}
CookieJar是OkHttp的Cookie管理器,它負責Cookie的存取。源碼如下:
下面是OkHttpClient默認的構造器,其中CookieJar爲CookieJar.NO_COOKIES。(即我們上面的源碼所示)
由OkHttpClient默認構造過程可以看到,OkHttp中默認是沒有提供Cookie管理功能的。由CookieJar的源碼可以看出,如果想要支持cookie的話,也就只是實現那兩個方法。
CacheInterceptor
在執行完RetryAndFollowUpInterceptor之後,執行我們的CacheInterceptor,它主要用於處理緩存。
對於CacheInterceptor.intercept(Chain chain)的分析同樣可以分爲兩個階段,即發送請求之前和獲取響應之後。
發送請求之前的代碼:
在請求發送階段,主要是嘗試從cache中獲取響應,獲取成功的話,且響應可用未過期,則響應會被直接返回;
@Override public Response intercept(Chain chain) throws IOException {
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
if (cache != null) {
cache.trackResponse(strategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// If we're forbidden from using the network and the cache is insufficient, fail.
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
// If we don't need the network, we're done.
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
Response networkResponse = null;
try {
獲取響應之後的代碼:
通過後續的Interceptor來從網絡獲取,獲取到響應之後,若需要緩存的,則緩存起來。
networkResponse = chain.proceed(networkRequest);
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
// If we have a cache response too, then we're doing a conditional get.
if (cacheResponse != null) {
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
cache.trackConditionalCacheHit();
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
if (cache != null) {
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
由RealCall.getResponseWithInterceptorChain()可見CacheInterceptor的cache同樣來自於OkHttpClient。OkHttp已經有實現Cache的整套策略,在Cache類,但默認情況下不會被用起來,需要自己在創建OkHttpClient時,手動創建並傳給OkHttpClient.Builder。
下面是默認情況的代碼:(從代碼中可以看出沒有Cache的配置)
ConnectInterceptor
ConnectInterceptor的主要職責是建立與服務器之間的連接,但這個事情它主要是委託給StreamAllocation來完成的。如我們前面看到的,StreamAllocation對象是在RetryAndFollowUpInterceptor中分配的。(這裏連接的建立過程先不展開敘述,後續會專門講述StreamAllocation)
ConnectInterceptor通過StreamAllocation創建了HttpStream對象和RealConnection對象,隨後便調用了realChain.proceed(),向連接中寫入HTTP請求,並從服務器讀迴響應。
CallServerInterceptor
如果請求的header或服務器響應的header中,Connection值爲close,CallServerInterceptor還會關閉連接。
最後便是返回Response。
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
HttpCodec httpCodec = realChain.httpStream();
StreamAllocation streamAllocation = realChain.streamAllocation();
RealConnection connection = (RealConnection) realChain.connection();
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
realChain.eventListener().requestHeadersStart(realChain.call());
//CallServerInterceptor首先將http請求頭部發給服務器
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
Response.Builder responseBuilder = null;
//如果http請求有body的話,會再將body發送給服務器,
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
// If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
// Continue" response before transmitting the request body. If we don't get that, return
// what we did get (such as a 4xx response) without ever transmitting the request body.
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
httpCodec.flushRequest();
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(true);
}
if (responseBuilder == null) {
// Write the request body if the "Expect: 100-continue" expectation was met.
realChain.eventListener().requestBodyStart(realChain.call());
long contentLength = request.body().contentLength();
CountingSink requestBodyOut =
new CountingSink(httpCodec.createRequestBody(request, contentLength));
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
realChain.eventListener()
.requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
} else if (!connection.isMultiplexed()) {
// If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
// from being reused. Otherwise we're still obligated to transmit the request body to
// leave the connection in a consistent state.
streamAllocation.noNewStreams();
}
}
//通過httpStream.finishRequest()結束http請求的發送。
httpCodec.finishRequest();
//從連接中讀取服務器返回的http響應,並構造Response。
if (responseBuilder == null) {
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(false);
}
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
realChain.eventListener()
.responseHeadersEnd(realChain.call(), response);
int code = response.code();
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
response = response.newBuilder()
.body(Util.EMPTY_RESPONSE)
.build();
} else {
response = response.newBuilder()
.body(httpCodec.openResponseBody(response))
.build();
}
//如果請求的header或服務器響應的header中Connection值爲close,
CallServerInterceptor還會關閉連接。
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
streamAllocation.noNewStreams();
}
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
小總結
RetryAndFollowUpInterceptor :
創建StreamAllocation對象,處理http的redirect,出錯重試。
對後續Interceptor的執行的影響:修改request及StreamAllocation。
BridgeInterceptor:
補全缺失的一些http header。
對後續Interceptor的執行的影響:修改request。
CacheInterceptor:
處理http緩存。
對後續Interceptor的執行的影響:若緩存中有所需請要的響應,則後續Interceptor不再執行。
ConnectInterceptor:
藉助於前面分配的StreamAllocation對象建立與服務器之間的連接,並選定交互所用的協議是HTTP 1.1還是HTTP 2。
對後續Interceptor的執行的影響:創建了httpStream和connection。
CallServerInterceptor:
處理IO,與服務器進行數據交換。
對後續Interceptor的執行的影響:爲Interceptor鏈中的最後一個Interceptor,沒有後續Interceptor。