okhttp3.6.0源碼分析系列文章整體內(nèi)容如下:
一 okhttp默認(rèn)的攔截器
okhttp默認(rèn)執(zhí)行的攔截器有五個(gè):
- RetryAndFollowUpInterceptor 重定向攔截器
- BridgeInterceptor 該攔截器是鏈接客戶端代碼和網(wǎng)絡(luò)代碼的橋梁船殉,它首先將客戶端構(gòu)建的Request對(duì)象信息構(gòu)建成真正的網(wǎng)絡(luò)請(qǐng)求;然后發(fā)起網(wǎng)絡(luò)請(qǐng)求,最后是將服務(wù)器返回的消息封裝成一個(gè)Response對(duì)象。
- CacheInterceptor 緩存攔截器
- ConnectInterceptor 打開(kāi)與服務(wù)器的連接
- CallServerInterceptor 開(kāi)啟與服務(wù)器的網(wǎng)絡(luò)請(qǐng)求
1.1 攔截器調(diào)用
不管是同步請(qǐng)求還是異步請(qǐng)求都會(huì)調(diào)用
Response response = getResponseWithInterceptorChain();
來(lái)獲取網(wǎng)絡(luò)請(qǐng)求內(nèi)容,下面來(lái)看下getResponseWithInterceptorChain()里面是如何實(shí)現(xiàn)的:
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));
//將攔截器封裝成InterceptorChain,注意 時(shí)候 index為0
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
從getResponseWithInterceptorChain方法返回時(shí)調(diào)用的chain.proceed(originalRequest)開(kāi)始分析,該方法調(diào)用RealInterceptorChain的procees方法:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
calls++;
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request); //構(gòu)造一個(gè)RealInterceptorChain,新的RealInterceptorChain的index為1
Interceptor interceptor = interceptors.get(index); //傳入的index為0盐杂,所以為調(diào)用第一個(gè)攔截器,假如沒(méi)有沒(méi)有添加自定義的攔截器哆窿,interceptor是RetryAndFollowUpInterceptor
Response response = interceptor.intercept(next); //調(diào)用的是RetryAndFollowUpInterceptor里的intercept方法
return response;
}
RetryAndFollowUpInterceptor中intercept方法:
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response = null;
boolean releaseConnection = true;
try {
// 再次調(diào)用 RealInterceptorChain的proceed方法链烈,注意這里streamAllocation不為null
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
priorResponse = response;
}
}
再次進(jìn)入RealInterceptorChain的proceed方法:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
calls++;
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request); //構(gòu)造一個(gè)RealInterceptorChain,新的RealInterceptorChain的index為2
Interceptor interceptor = interceptors.get(index); //傳入的index為1挚躯,所以為調(diào)用第二個(gè)攔截器强衡,假如沒(méi)有沒(méi)有添加自定義的攔截器,interceptor是BridgeInterceptor
Response response = interceptor.intercept(next); //調(diào)用的是BridgeInterceptor 里的intercept方法
return response;
}
進(jìn)入BridgeInterceptor 里的intercept方法:
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
//對(duì)請(qǐng)求報(bào)文進(jìn)行處理
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());
}
//到這里為止又會(huì)進(jìn)行新的回調(diào)码荔,會(huì)再次進(jìn)入RealInterceptorChain方法中去
Response networkResponse = chain.proceed(requestBuilder.build());
//下面的代碼會(huì)在上面的回調(diào)出棧之后才會(huì)調(diào)用漩勤,那時(shí)候網(wǎng)絡(luò)請(qǐng)求已經(jīng)完成,已經(jīng)得到網(wǎng)絡(luò)相應(yīng)內(nèi)容缩搅,這時(shí)候?qū)憫?yīng)報(bào)文進(jìn)行處理
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);
responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
BridgeInterceptor 中的 chain.proceed(requestBuilder.build());放在intercept方法request信息組裝成功之后越败,這樣等到請(qǐng)求結(jié)束,就可以在拿到response之后對(duì)響應(yīng)內(nèi)容進(jìn)行處理了硼瓣,這種實(shí)現(xiàn)方式太優(yōu)雅了究飞。
在運(yùn)行proceed方法時(shí)又會(huì)跳轉(zhuǎn)到RealInterceptorChain的procees方法:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
calls++;
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request); //構(gòu)造一個(gè)RealInterceptorChain,新的RealInterceptorChain的index為3
Interceptor interceptor = interceptors.get(index); //傳入的index為2巨双,所以為調(diào)用第三個(gè)攔截器噪猾,假如沒(méi)有沒(méi)有添加自定義的攔截器霉祸,interceptor是CacheInterceptor
Response response = interceptor.intercept(next); //調(diào)用的是CacheInterceptor里的intercept方法
return response;
}
CacheInterceptor里的intercept方法:
@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;
}
networkResponse = chain.proceed(networkRequest);
proceed方法之前的部分是若是配置了緩存策略筑累,并且有緩存,則直接取出丝蹭,不再進(jìn)行網(wǎng)絡(luò)請(qǐng)求慢宗,鏈?zhǔn)秸{(diào)用也終止。
proceed方法執(zhí)行之后的部分會(huì)根據(jù)緩存策略奔穿,對(duì)網(wǎng)絡(luò)相應(yīng)內(nèi)容進(jìn)行存儲(chǔ)镜沽。
在調(diào)用chain.proceed時(shí),再次進(jìn)入RealInterceptorChain的proceed方法:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
calls++;
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request); //構(gòu)造一個(gè)RealInterceptorChain贱田,新的RealInterceptorChain的index為4
Interceptor interceptor = interceptors.get(index); //傳入的index為3缅茉,所以為調(diào)用第四個(gè)攔截器,假如沒(méi)有沒(méi)有添加自定義的攔截器男摧,interceptor是ConnectInterceptor
Response response = interceptor.intercept(next); //調(diào)用的是ConnectInterceptor 里的intercept方法
return response;
}
ConnectInterceptor 里的intercept方法:
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
//獲取在RetryAndFollowUpInterceptor中構(gòu)建的streamAllocation
StreamAllocation streamAllocation = realChain.streamAllocation();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
//構(gòu)建HttpCodec 對(duì)象
HttpCodec httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks);
//構(gòu)建RealConnection 對(duì)象
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
ConnectInterceptor 里的intercept方法比較少蔬墩,主要是為下一步網(wǎng)絡(luò)請(qǐng)求做準(zhǔn)備译打;
方法結(jié)束時(shí)調(diào)用realChain.proceed再次進(jìn)入RealInterceptorChain的proceed方法:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
calls++;
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request); //構(gòu)造一個(gè)RealInterceptorChain,新的RealInterceptorChain的index為5
Interceptor interceptor = interceptors.get(index); //傳入的index為4拇颅,所以為調(diào)用第五個(gè)攔截器奏司,假如沒(méi)有沒(méi)有添加自定義的攔截器,interceptor是CallServerInterceptor樟插,這也是最后一個(gè)攔截器
Response response = interceptor.intercept(next); //調(diào)用的是ConnectInterceptor 里的intercept方法
return 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();
httpCodec.writeRequestHeaders(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();
responseBuilder = httpCodec.readResponseHeaders(true);
}
if (responseBuilder == null) {
// Write the request body if the "Expect: 100-continue" expectation was met.
Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
} 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) {
responseBuilder = httpCodec.readResponseHeaders(false);
}
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
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;
}
將請(qǐng)求報(bào)文通過(guò)socket傳到服務(wù)端韵洋,讀取響應(yīng)報(bào)文,然后返回黄锤,終止鏈?zhǔn)秸{(diào)用搪缨。一層一層返回。
二 用戶自定義攔截器
除了okhttp自定義的攔截器之外猜扮,用戶也可以給自定義攔截器勉吻。
自定義的攔截器分為兩種:
- 應(yīng)用層攔截器,使用場(chǎng)景是:
- Don't need to worry about intermediate responses like redirects and retries.
- Are always invoked once, even if the HTTP response is served from the cache.
- Observe the application's original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
- Permitted to short-circuit and not call Chain.proceed().
- Permitted to retry and make multiple calls to Chain.proceed().
- 網(wǎng)絡(luò)層攔截器旅赢,使用場(chǎng)景是:
- Able to operate on intermediate responses like redirects and retries.
- Not invoked for cached responses that short-circuit the network.
- Observe the data just as it will be transmitted over the network.
- Access to the Connection that carries the request.
攔截器添加的源碼如下:
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);
return chain.proceed(originalRequest);
}
攔截器執(zhí)行流程如下所示:
上面的這些使用場(chǎng)景結(jié)合源碼看就很容易理解了齿桃。
2.1 應(yīng)用層攔截器
client.interceptors獲取的攔截器就是應(yīng)用層的攔截器,會(huì)在所有攔截器之前處理request煮盼,這時(shí)候的request是沒(méi)有被系統(tǒng)攔截器修改過(guò)的泪漂。
如果要攔截網(wǎng)絡(luò)異常并上報(bào),那么應(yīng)該使用這類攔截器悟泵。
2.2 網(wǎng)絡(luò)層攔截器
client.networkInterceptions()返回的是網(wǎng)絡(luò)層攔截器图柏,可以看出它拿到的request可能會(huì)被重定向,而且如果開(kāi)啟了網(wǎng)絡(luò)緩存报破,那么是這類攔截器將不會(huì)被調(diào)用悠就。因?yàn)樗亲詈蟊徽{(diào)用的,所以它能拿到最終被傳輸?shù)恼?qǐng)求充易,也是我們最后能夠處理請(qǐng)求的機(jī)會(huì)梗脾。
facebook的stetho定義的攔截器StethoInterceptor就是一種網(wǎng)絡(luò)層連接器:
new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
(完)