OkHttp3原始碼解析
在OkHttp3中,其靈活性很大程度上體現在可以 intercept
其任意一個環節,而這個優勢便是okhttp3整個請求響應架構體系的精髓所在,先放出一張主框架請求流程圖,接著再分析原始碼。
Okhttp請求流程
String url = "http://wwww.baidu.com"; OkHttpClient okHttpClient = new OkHttpClient(); final Request request = new Request.Builder() .url(url) .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure: "); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG, "onResponse: " + response.body().string()); } });
這大概是一個最簡單的一個例子了,在new OkHttpClient()
內部使用構造器模式初始化了一些配置資訊:支援協議、任務分發器(其內部包含一個執行緒池,執行非同步請求)、連線池(其內部包含一個執行緒池,維護connection)、連線/讀/寫超時時長等資訊。
public Builder() { dispatcher = new Dispatcher(); //任務排程器 protocols = DEFAULT_PROTOCOLS; //支援的協議 connectionSpecs = DEFAULT_CONNECTION_SPECS; eventListenerFactory = EventListener.factory(EventListener.NONE); proxySelector = ProxySelector.getDefault(); cookieJar = CookieJar.NO_COOKIES; socketFactory = SocketFactory.getDefault(); hostnameVerifier = OkHostnameVerifier.INSTANCE; certificatePinner = CertificatePinner.DEFAULT; proxyAuthenticator = Authenticator.NONE; authenticator = Authenticator.NONE; connectionPool = new ConnectionPool(); //連線池 dns = Dns.SYSTEM; followSslRedirects = true; followRedirects = true; retryOnConnectionFailure = true; connectTimeout = 10_000;//超時時間 readTimeout = 10_000; writeTimeout = 10_000; pingInterval = 0; }
第一行建立了一個Dispatcher
任務排程器,它定義了三個雙向任務佇列,兩個非同步佇列:準備執行的請求佇列 readyAsyncCalls
、正在執行的請求佇列 runningAsyncCalls
;一個正在執行的同步請求佇列 runningSyncCalls
;
public final class Dispatcher { private int maxRequests = 64; //最大請求數量 private int maxRequestsPerHost = 5; //每臺主機最大的請求數量 private @Nullable Runnable idleCallback; /** Executes calls. Created lazily. */ private @Nullable ExecutorService executorService; //執行緒池 /** Ready async calls in the order they'll be run. */ private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */ private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); /** Running synchronous calls. Includes canceled calls that haven't finished yet. */ private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>(); /** 這個執行緒池沒有核心執行緒,執行緒數量沒有限制,空閒60s就會回收*/ public synchronized ExecutorService executorService() { if (executorService == null) { executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false)); } return executorService; } }
另外還有一個執行緒池 executorService
,這個執行緒池跟Android中的CachedThreadPool非常類似,這種型別的執行緒池,適用於大量的耗時較短的非同步任務。下一篇文章 將對OkHttp框架中的執行緒池做一個總結。
接下來接著看Request的構造,這個例子Request比較簡單,指定了請求方式 GET
和請求 url
public static class Builder {
HttpUrl url;
String method;
Headers.Builder headers;
RequestBody body;
Object tag;
public Builder() {
this.method = "GET";
this.headers = new Headers.Builder();
}
public Builder url(HttpUrl url) {
if (url == null) throw new NullPointerException("url == null");
this.url = url;
return this;
}
public Request build() {
if (url == null) throw new IllegalStateException("url == null");
return new Request(this);
}
...
}
緊接著通過 OkHttpClient
和 Request
構造一個 Call
物件,它的實現是RealCall
public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket){
// Safely publish the Call instance to the EventListener.
RealCall call = new RealCall(client, originalRequest, forWebSocket);
call.eventListener = client.eventListenerFactory().create(call);
return call;
}
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
}
可以看到在 RealCall
的構造方法中建立了一個RetryAndFollowUpInterceptor
,用於處理請求錯誤和重定向等,這是 Okhttp
框架的精髓 interceptor chain
中的一環,預設情況下也是第一個攔截器,除非呼叫 OkHttpClient.Builder#addInterceptor(Interceptor)
來新增全域性的攔截器。關於攔截器鏈的順序參見 RealCall#getResponseWithInterceptorChain()
方法。
RealCall#enqueue(Callback)
public void enqueue(Callback responseCallback) {
synchronized (this) {
//每個請求只能之執行一次
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
可以看到,一個 Call
只能執行一次,否則會拋異常,這裡建立了一個 AsyncCall
並將Callback傳入,接著再交給任務分發器 Dispatcher
來進一步處理。
synchronized void enqueue(AsyncCall call) {
//正在執行的任務數量小於最大值(64),並且此任務所屬主機的正在執行任務小於最大值(5)
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
從 Dispatcher#enqueue()
方法的策略可以看出,對於請求的入隊做了一些限制,若正在執行的請求數量小於最大值(預設64),並且此請求所屬主機的正在執行任務小於最大值(預設5),就加入正在執行的佇列並通過執行緒池來執行該任務,否則加入準備執行佇列中。
- 流程圖
現在回頭看看 AsyncCall
,它繼承自 NamedRunnable
,而 NamedRunnable
實現了 Runnable
介面,它的作用有2個:
①採用模板方法的設計模式,讓子類將具體的操作放在 execute()
方法中;
②給執行緒指定一個名字,比如傳入模組名稱,方便監控執行緒的活動狀態;
public abstract class NamedRunnable implements Runnable {
protected final String name;
public NamedRunnable(String format, Object... args) {
this.name = Util.format(format, args);
}
@Override public final void run() {
String oldName = Thread.currentThread().getName();
Thread.currentThread().setName(name);
try {
//採用模板方法讓子類將具體的操作放到此execute()方法
execute();
} finally {
Thread.currentThread().setName(oldName);
}
}
protected abstract void execute();
}
final class AsyncCall extends NamedRunnable {
//省略...
@Override protected void execute() {
boolean signalledCallback = false;
try {
//呼叫 getResponseWithInterceptorChain()獲得響應內容
Response response = getResponseWithInterceptorChain(); //①
if (retryAndFollowUpInterceptor.isCanceled()) {
//這個標記為主要是避免異常時2次回撥
signalledCallback = true;
//回撥Callback告知失敗
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
//回撥Callback,將響應內容傳回去
responseCallback.onResponse(RealCall.this, response);
}
} catch (IOException e) {
if (signalledCallback) {
// Do not signal the callback twice!
Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
} else {
eventListener.callFailed(RealCall.this, e);
responseCallback.onFailure(RealCall.this, e);
}
} finally {
//不管請求成功與否,都進行finished()操作
client.dispatcher().finished(this);//②
}
}
}
先看註釋②的行finally塊中執行的 client.dispatcher().finished(this)
void finished(AsyncCall call) {
finished(runningAsyncCalls, call, true);
}
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
int runningCallsCount;
Runnable idleCallback;
synchronized (this) {
//從正在執行的佇列中將其移除
if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
if (promoteCalls) promoteCalls(); //推動下一個任務的執行
runningCallsCount = runningCallsCount();//同步+非同步的正在執行任務數量
idleCallback = this.idleCallback;
}
//如果沒有正在執行的任務,且idleCallback不為null,則回撥通知空閒了
if (runningCallsCount == 0 && idleCallback != null) {
idleCallback.run();
}
}
其中promoteCalls()
為推動下一個任務執行,其實它做的也很簡單,就是在條件滿足的情況下,將 readyAsyncCalls
中的任務移動到 runningAsyncCalls
中,並交給執行緒池來執行,以下是它的實現。
private void promoteCalls() {
if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
//若條件允許,將readyAsyncCalls中的任務移動到runningAsyncCalls中,並交給執行緒池執行
for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall call = i.next();
if (runningCallsForHost(call) < maxRequestsPerHost) {
i.remove();
runningAsyncCalls.add(call);
executorService().execute(call);
}
//當runningAsyncCalls滿了,直接退出迭代
if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
}
}
接下來就回到註釋①處的響應內容的獲取 getResponseWithInterceptorChain()
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>(); //這是一個List,是有序的
interceptors.addAll(client.interceptors());//首先新增的是使用者新增的全域性攔截器
interceptors.add(retryAndFollowUpInterceptor); //錯誤、重定向攔截器
//橋接攔截器,橋接應用層與網路層,新增必要的頭、
interceptors.add(new BridgeInterceptor(client.cookieJar()));
//快取處理,Last-Modified、ETag、DiskLruCache等
interceptors.add(new CacheInterceptor(client.internalCache()));
//連線攔截器
interceptors.add(new ConnectInterceptor(client));
//從這就知道,通過okHttpClient.Builder#addNetworkInterceptor()傳進來的攔截器只對非網頁的請求生效
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);
}
可以看這塊重點就是 interceptors
這個集合,首先將前面的 client.interceptors()
全部加入其中,還有在建立 RealCall
時的 retryAndFollowUpInterceptor
加入其中,接著還建立並添加了BridgeInterceptor、CacheInterceptor、ConnectInterceptor、CallServerInterceptor
,最後通過RealInterceptorChain#proceed(Request)
來執行整個 interceptor chain
,可見把這個攔截器鏈搞清楚,整體流程也就明朗了。
RealInterceptorChain#proceed()
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 {
//省略異常處理...
// 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);
//省略異常處理...
return response;
}
從這段實現可以看出,是按照新增到 interceptors
集合的順序,逐個往下呼叫攔截器的intercept()方法,所以在前面的攔截器會先被呼叫。這個例子中自然就是 RetryAndFollowUpInterceptor
了。
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
//建立一個StreamAllocation
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
//統計重定向次數,不能大於20
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//呼叫下一個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(), streamAllocation, 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, streamAllocation, 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, streamAllocation.route());
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);
this.streamAllocation = streamAllocation;
} 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;
}
}
這個攔截器就如同它的名字retry and followUp
,主要負責錯誤處理和重定向等問題,比如路由錯誤、IO異常等。
接下來就到了BridgeInterceptor#intercept()
,在這個攔截器中,添加了必要請求頭資訊,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) {
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();
}
這個攔截器處理請求資訊、cookie、gzip等,接著往下是 CacheInterceptor
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;
}
這個攔截器主要工作是做做快取處理,如果有有快取並且快取可用,那就使用快取,否則進行呼叫下一個攔截器 ConnectionInterceptor
進行網路請求,並將響應內容快取。
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);
}
這個攔截器主要是開啟一個到目標伺服器的 connection
並呼叫下一個攔截器 CallServerInterceptor
,這是攔截器鏈最後一個攔截器,它向伺服器發起真正的網路請求。
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();
int code = response.code();
if (code == 100) {
// server sent a 100-continue even though we did not request one.
// try again to read the actual response
responseBuilder = httpCodec.readResponseHeaders(false);
response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
realChain.eventListener()
.responseHeadersEnd(realChain.call(), response);
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;
}
從上面的請求流程圖可以看出,OkHttp的攔截器鏈可謂是其整個框架的精髓,使用者可傳入的 interceptor 分為兩類: ①一類是全域性的 interceptor,該類 interceptor 在整個攔截器鏈中最早被呼叫,通過 OkHttpClient.Builder#addInterceptor(Interceptor) 傳入; ②另外一類是非網頁請求的 interceptor ,這類攔截器只會在非網頁請求中被呼叫,並且是在組裝完請求之後,真正發起網路請求前被呼叫,所有的 interceptor 被儲存在 List<Interceptor> interceptors 集合中,按照新增順序來逐個呼叫,具體可參考 RealCall#getResponseWithInterceptorChain() 方法。通過 OkHttpClient.Builder#addNetworkInterceptor(Interceptor) 傳入;