一、攔截器鏈流程圖
二滩字、getResponseWithInterceptorChain 方法
之前說到主要是通過這個方法來返回response那么來看看這個方法里究竟是做了什么呢
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);
}
首先添加自定義配置的攔截器
然后以此添加系統(tǒng)內(nèi)置的攔截器
然后創(chuàng)建RealInterceptorChain并把這個集合添加進(jìn)去透敌,這個就是個攔截器鏈
通過chain.proceed(originalRequest);這個方法執(zhí)行
proceed這個方法也很重要 可以看一下
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;
}
這里主要看標(biāo)注的注意處 這里主要通過index+1創(chuàng)建了下一個攔截器,也就行程了攔截器鏈
然后通過每個攔截器中都有intercept這個方法踢械,這個方法中返回response然后進(jìn)行返回。
這里有個流程是很有意思的就是在proceed()方法里會會返回一個Response 而 這個Response是通過intercep()這個方法并傳入一個攔截器返回的魄藕,而在各個攔截器中又通過傳入的攔截器調(diào)回去内列,這也是攔截器流程的核心機(jī)制。從而實(shí)現(xiàn)了攔截器鏈背率,只有所有的攔截器執(zhí)行完畢后话瞧,一個網(wǎng)絡(luò)請求的響應(yīng)response 才會被返回。
三寝姿、內(nèi)置攔截器
OkHttp中的內(nèi)置連接器都基實(shí)現(xiàn)了通用的接口
1交排、RetryAndFollowUpInterceptor 接口重定向攔截器
這個攔截器主要是根據(jù)結(jié)果判斷然后進(jìn)行重試的攔截器
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {//注意處1
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {//注意處2
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();
}
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()), 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;
}
}
具體分析下流程
首先會創(chuàng)建一個StreamAllocation對象
其實(shí)主要看while循環(huán)里面的方法,這里是一個死循環(huán)來進(jìn)行嘗試饵筑,首先會判斷是否取消了請求埃篓,如果取消進(jìn)行釋放,并拋出異常根资,如注意處1.
然后主注意處2要進(jìn)行請求架专,然后通過catch判斷各種需要重新連接的情況,如果重新連接就通過continue直接在進(jìn)行一遍循環(huán)玄帕。
當(dāng)代碼可以執(zhí)行到 followUpRequest 方法就表示這個請求是成功的部脚,但是服務(wù)器返回的狀態(tài)碼可能不是 200 ok 的情況,這時還需要對該請求進(jìn)行檢測裤纹,其主要就是通過返回碼進(jìn)行判斷的委刘,然后如果沒問題就會返回respnse并結(jié)束循環(huán)。
如果沒有正常返回結(jié)果的話后面會關(guān)閉請求還會做一些異常檢查鹰椒,如重新連接的次數(shù)是否超過了最大次數(shù)之類的锡移。
2、BridgeInterceptor 請求和響應(yīng)轉(zhuǎn)化攔截器
這個攔截器主要負(fù)責(zé)設(shè)置內(nèi)容長度吹零,編碼方式以及一些壓縮等配置罩抗,主要是添加頭部信息的功能。
@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());
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();
}
這里通過注意出可以看到其中一個主要的功能就是灿椅,如果剛開始我們沒有配置一些請求頭信息會添加一些默認(rèn)的請求頭信息套蒂。
這里還有一個重要功能就是 判斷是否需要使用Gzip壓縮功能钞支。以及將網(wǎng)絡(luò)請求回來的響應(yīng)Response轉(zhuǎn)化為永華可用的response
3、CacheInterceptor 緩存攔截器
@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 {
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;
}
主要流程操刀,先判斷是否有緩存烁挟。然后如果緩存不可用會關(guān)閉,然后在會判斷網(wǎng)絡(luò)禁止的話和緩存都不可用的話會創(chuàng)建一個響應(yīng)返回504
// 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();
}
如果前面的條件都不符合骨坑,會讀取網(wǎng)絡(luò)結(jié)果也就是會跳轉(zhuǎn)到下一個攔截器撼嗓, if (networkResponse.code() == HTTP_NOT_MODIFIED) 這里會判斷如果是304的話使用緩存,還會對緩存進(jìn)行比對和更新欢唾。然后并返回response且警。在這之前會先判斷cacheResponse是否為空,如果為空則走后面的代碼礁遣,會創(chuàng)建一個response斑芜。
4、ConnectInterceptor 網(wǎng)絡(luò)連接攔截器
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
StreamAllocation streamAllocation = realChain.streamAllocation();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
這里的StreamAllocation其實(shí)是在重定向攔截器中創(chuàng)建祟霍,但是他傳入到ConnectInterceptor中進(jìn)行使用杏头。然后會通過streamAllocation來創(chuàng)建httpCodec,httpCodec用來編碼request和解碼response沸呐。然后會通過streamAllocation.connection();來創(chuàng)建一個RealConnection醇王,RealConnection主要來進(jìn)行實(shí)際的網(wǎng)絡(luò)傳輸。然后還是通過proceed方法傳入到下一個攔截器崭添。
5寓娩、CallServerInterceptor
這個攔截器是攔截器鏈中最后一個攔截器,是真正的發(fā)起請求和處理返回響應(yīng)的攔截器滥朱。
@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());
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), request);
Response.Builder responseBuilder = null;
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();
}
}
httpCodec.finishRequest();
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();
}
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;
}
流程
這里首先會獲取到之前各個攔截器中的一些參數(shù)根暑,首先會 httpCodec.writeRequestHeaders(request);通過這個httpCodec寫入請求頭信息,然后會寫入請求的body信息徙邻,完成寫入后會調(diào)用 httpCodec.finishRequest();
方法表示寫入信息完成排嫌。
然后會讀取響應(yīng)信息,會先讀取響應(yīng)頭信息缰犁,響應(yīng)如果讀取或者創(chuàng)建完成后會 通過streamAllocation.noNewStreams();這個方法進(jìn)行關(guān)閉流淳地,還會判斷如果響應(yīng)碼是204或者205的話拋出一個異常。
其實(shí)這個攔截器鏈無非就是2個工作帅容,發(fā)起請求颇象,然后處理響應(yīng)。至于中間會有一些封裝請求信息判斷響應(yīng)信息等操作并徘。
四遣钳、總結(jié)
這里攔截器的流程基本分析完了,其實(shí)主要還是看清大體流程和設(shè)計思路麦乞,具體細(xì)節(jié)的部分沒有過多深入蕴茴,因?yàn)檫@些流程設(shè)計模式才是真正要學(xué)習(xí)的重點(diǎn)劝评。從源碼看來 好多地方還是很值得學(xué)習(xí)的。