OkHttp源碼分析
在現(xiàn)在的Android開發(fā)中,請求網(wǎng)絡獲取數(shù)據(jù)基本上成了我們的標配。在早期的Android開發(fā)中會有人使用HttpClient、HttpUrlConnection或者Volley等網(wǎng)絡請求方式,但對于如今(2018年)而言,絕大多數(shù)的開發(fā)者都會使用OkHttp+Retrofit+RxJava進行網(wǎng)絡請求,而對于這三者而言,實際請求網(wǎng)絡的框架是OkHttp,所以OkHttp的重要性不言而喻。
OkHttp的基本用法
//創(chuàng)建OkHttpClient對象
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
//創(chuàng)建Request請求對象
Request request = new Request.Builder()
.url(url)
.build();
//創(chuàng)建Call對象,并執(zhí)行同步獲取網(wǎng)絡數(shù)據(jù)
Response response = client.newCall(request).execute();
return response.body().string();
}
使用OkHttp基本是以下四步:
- 創(chuàng)建OkHttpClient對象
- 創(chuàng)建Request請求對象
- 創(chuàng)建Call對象
- 同步請求調用call.execute();異步請求調用call.enqueue(callback)
接下來我會對這四步進行詳細的說明。
創(chuàng)建OkHttpClient對象
通常來說,我們使用OkHttp并不會直接通過new OkHttpClient()來創(chuàng)建出一個OkHttpClient。一般來說,我們會對這個OkHttpClient做一些配置,比如:
OkHttpClient.Builder().connectTimeout(
DEFAULT_MILLISECONDS, TimeUnit.SECONDS).readTimeout(
DEFAULT_MILLISECONDS, TimeUnit.SECONDS).addInterceptor { chain ->
val builder = chain.request().newBuilder()
headerMap?.forEach {
builder.addHeader(it.key, it.value)
}
val request = builder.build()
chain.proceed(request)
}.addInterceptor(httpLoggingInterceptor).build()
上面是一段使用Kotlin代碼創(chuàng)建OkHttpClient的過程,很明顯,OkHttpClient內部是使用了 Builder 模式,好處很明顯: 我們在創(chuàng)建對象的同時可以自由的配置我們需要的參數(shù) 。我們簡單看一下OkHttpClient內部類Builder中的構造方法,看一下OkHttpClient內部都可以做哪些配置:
public Builder() {
//默認的分發(fā)器
dispatcher = new Dispatcher();
protocols = DEFAULT_PROTOCOLS;
connectionSpecs = DEFAULT_CONNECTION_SPECS;
//事件監(jiān)聽工廠
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;
//默認連接超時10s
connectTimeout = 10_000;
//默認讀取超時10s
readTimeout = 10_000;
//默認寫入超時10s
writeTimeout = 10_000;
pingInterval = 0;
}
上面的代碼中我們非常熟悉的就是連接超時、讀取超時、寫入超時,它們的默認事件都是10s,其實這也提醒我們,如果我們想要設置的超時時間也是10s的話,完全沒有必要重復進行配置,其實我的建議也是不需要配置,直接使用默認的就好。值得注意的是 Dispatcher 這個類,這是一個網(wǎng)絡請求的分發(fā)器,主要作用是在同步,異步網(wǎng)絡請求時會做一些不同的分發(fā)處理,我們先有個印象即可, Dispatcher 會在之后詳細的分析。
可能細心的小伙伴這時候會說了:我平時會對OkHttpClient加上一些interceptor來攔截網(wǎng)絡請求,比方說在請求之前加上token等請求頭之類的,上面這段代碼為什么沒有攔截器相關的變量呢?
沒錯,OkHttpClient中的Builder類內部確實是有攔截器相關成員變量,只不過沒寫在Builder的構造方法內:
public static final class Builder {
//省略無關代碼......
final List<Interceptor> interceptors = new ArrayList<>();
final List<Interceptor> networkInterceptors = new ArrayList<>();
//省略無關代碼......
}
我們平常添加的interceptor就存放在interceptors這個ArrayList中。OkHttpClient對象的配置創(chuàng)建不是什么難以理解的點,接下來我們看Request對象的創(chuàng)建。
創(chuàng)建Request請求對象
為什么要創(chuàng)建Request對象,很簡單,我們請求網(wǎng)絡需要一些必要的參數(shù),比如url,請求方式是get或者post等等信息。而Request這個類就是對這些網(wǎng)絡請求參數(shù)的統(tǒng)一封裝??匆幌麓a就一目了然了:
public final class Request {
final HttpUrl url;
final String method;
final Headers headers;
final @Nullable RequestBody body;
final Object tag;
private volatile CacheControl cacheControl; // Lazily initialized.
//省略無關代碼......
}
相信大家都能看明白,這個Request類中封裝了url、請求方式、請求頭、請求體等等網(wǎng)絡請求相關的信息。Request里面也是一個Builder模式,這里就不贅述了。
創(chuàng)建Call對象
Call對象我們可以這樣理解:Call對象是對 一次 網(wǎng)絡請求的封裝。注意這個關鍵字: 一次 ,熟悉OkHttp的同學應該都知道,一個Call對象只能被執(zhí)行一次,不論是同步execute還是異步的enqueue,那么這個只能執(zhí)行一次的特性是如何保證的呢?我們來看代碼:
@Override public Call newCall(Request request) {
//實際上是通過 RealCall.newRealCall 來獲取Call對象
return RealCall.newRealCall(this, request, false /* for web socket */);
}
上面的代碼能看到OkHttpClient的newCall實際上是通過RealCall.newRealCall(this, request, false /* for web socket */)來獲得的,我們來看一下這個RealCall:
final class RealCall implements Call {
final OkHttpClient client;
//錯誤重試與重定向攔截器
final RetryAndFollowUpInterceptor retryAndFollowUpInterceptor;
//監(jiān)聽OkHttp網(wǎng)絡請求各個階段的事件監(jiān)聽器
private EventListener eventListener;
final Request originalRequest;
final boolean forWebSocket;
//判斷Call對象是否被執(zhí)行過的標志變量
private boolean executed;
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
this.client = client;
this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket;
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
}
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
// Call只是一個接口,我們實際創(chuàng)建的是Call的實現(xiàn)類RealCall的對象
RealCall call = new RealCall(client, originalRequest, forWebSocket);
call.eventListener = client.eventListenerFactory().create(call);
return call;
}
Override public Response execute() throws IOException {
//確保線程安全的情況下通過executed來保證每個Call只被執(zhí)行一次
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
//省略無關代碼......
}
@Override public void enqueue(Callback responseCallback) {
/確保線程安全的情況下通過executed來保證每個Call只被執(zhí)行一次
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
//省略無關代碼
}
//省略無關代碼......
}
我們可以看到,Call只是一個接口,我們創(chuàng)建的實際上是RealCall對象。在RealCall中存在一個 execute 的成員變量,在execute()和enqueue(Callback responseCallback) 方法中都是通過 execute 來確保每個RealCall對象只會被執(zhí)行一次。
創(chuàng)建Call對象的過程其實也是很簡單的,麻煩的地方在最后一步: **execute()和enqueue(Callback responseCallback) **
同步請求與異步請求
前三步非常簡單,我們可以知道并沒有涉及網(wǎng)絡的請求,所以核心肯定是在這關鍵的第四步。
同步請求execute()和異步請求enqueue(Callback responseCallback)
先說同步請求,看代碼:
@Override public Response execute() throws IOException {
//通過executed確保每個Call對象只會被執(zhí)行一次
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
//網(wǎng)絡請求開始的回調
eventListener.callStart(this);
try {
//調用分發(fā)器的executed(this)方法
client.dispatcher().executed(this);
//真實的網(wǎng)絡請求是在這里處理的
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
//網(wǎng)絡請求失敗的回調
eventListener.callFailed(this, e);
throw e;
} finally {
//網(wǎng)絡請求結束
client.dispatcher().finished(this);
}
}
execute() 方法中首先通過executed確保每個Call對象只會被執(zhí)行一次,之后調用了eventListener.callStart(this);來執(zhí)行網(wǎng)絡請求開始的回調。接下來調用了client.dispatcher().executed(this),那么這句代碼具體是做了什么呢:
public Dispatcher dispatcher() {
//返回了一個OkHttpClient內部的dispather分發(fā)器
return dispatcher;
}
這句代碼首先返回一個 dispatcher ,這個分發(fā)器我們在上面也提到過,這是一個比較重要的概念,來看一下這個分發(fā)器:
public final class Dispatcher {
//最大請求數(shù)
private int maxRequests = 64;
//每個host的最大請求數(shù)
private int maxRequestsPerHost = 5;
//網(wǎng)絡請求處于空閑時的回調
private @Nullable Runnable idleCallback;
//線程池的實現(xiàn)
private @Nullable ExecutorService executorService;
//就緒等待網(wǎng)絡請求的異步隊列
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
//正在執(zhí)行網(wǎng)絡請求的異步隊列
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
//正在執(zhí)行網(wǎng)絡請求的同步隊列
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
//忽略無關代碼......
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
synchronized void executed(RealCall call) {
//將call對象加入網(wǎng)絡請求的同步隊列中
runningSyncCalls.add(call);
}
//忽略無關代碼......
}
可以看到 Dispatcher 這個分發(fā)器類內部定義了很多的成員變量:maxRequests 最大請求個數(shù),默認值是64; maxRequestsPerHost 每個host的最大請求個數(shù),這個host是什么?舉個栗子,一個URL為 http://gank.io/api ,那么host就是 http://gank.io/ 相當于baseUrl。 ** idleCallback** 這是一個空閑狀態(tài)時的回調,當我們的所有的網(wǎng)絡請求隊列為空時會執(zhí)行。 executorService 這是一個線程池,主要是為了高效執(zhí)行異步的網(wǎng)絡請求而創(chuàng)建的線程池,之后會再次提到它。接下來就是比較重要的三個隊列:
- readyAsyncCalls -> 在就緒等待的異步Call隊列
- runningAsyncCalls -> 正在執(zhí)行的異步Call隊列
- runningSyncCalls -> 正在執(zhí)行的同步Call隊列
對于這三個隊列來說,執(zhí)行同步請求的Call對象會加入到runningSyncCalls中;執(zhí)行異步請求的Call對象會加入到readyAsyncCalls或者runningAsyncCalls中,那么什么時候加入到等待隊列,什么時候加入到執(zhí)行隊列呢?簡單的說,如果執(zhí)行異步網(wǎng)絡請求的線程池很忙,異步請求的Call對象會加入到等待隊列;反之則加入到執(zhí)行隊列。那么這個忙于不忙的標準是什么呢?很簡單,在enqueue方法中有runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost一個判斷的標準,即正在執(zhí)行的異步隊列中Call對象個數(shù)小于maxRequests(64)并且執(zhí)行隊列中的同一個host對應的Call對象個數(shù)小于maxRequestsPerHost(5)的時候。
說完了 Dispatcher 關鍵的成員變量,我們來看一下它的 **executed(RealCall call) ** 方法:
synchronized void executed(RealCall call) {
//將call對象加入網(wǎng)絡請求的同步隊列中
runningSyncCalls.add(call);
}
這是一個synchronized修飾的方法,為了確保線程安全。Dispatcher中的executed(RealCall call)方法及其簡單,就是把Call對象加入到同步Call隊列中。對,你沒有看錯,它確實就只有這一行代碼,沒什么復雜的操作。
說完了 Dispatcher 中的同步方法,我們再來看一下異步:
synchronized void enqueue(AsyncCall call) {
//判斷Call對象應該添加到等待隊列還是執(zhí)行隊列
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
//加入執(zhí)行隊列
runningAsyncCalls.add(call);
//線程池開啟線程執(zhí)行異步網(wǎng)絡請求
executorService().execute(call);
} else {
//加入等待隊列
readyAsyncCalls.add(call);
}
}
和同步方法相比,異步方法中的內容要稍微多一點。首先是判斷Call對象應該添加到等待隊列還是執(zhí)行隊列,這個判斷上面已經說過。加入執(zhí)行隊列后,開啟線程池并執(zhí)行Call對象。這里需要注意的是異步請求時的Call對象和同步請求時不一樣,會轉換成一個 AsyncCall 對象,這個 AsyncCall 實際上是一個 NamedRunnable ,那既然是一個 Runnable ,我們肯定要看一下它的execute()方法:
@Override protected void execute() {
boolean signalledCallback = false;
try {
//核心的請求網(wǎng)絡方法
Response response = getResponseWithInterceptorChain();
if (retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
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 {
client.dispatcher().finished(this);
}
}
}
其實整段代碼看似非常多,核心就只有Response response = getResponseWithInterceptorChain()這一句:通過攔截器鏈獲取網(wǎng)絡返回結果。其實不止是異步請求,同步請求的核心也是這一行代碼。我們繼續(xù)看一下RealCall中的execute方法:
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
try {
client.dispatcher().executed(this);
//跟異步請求一樣,核心也是通過攔截器鏈來獲取網(wǎng)絡數(shù)據(jù)
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);
}
}
很明顯,在client.dispatcher().executed(this)將Call對象加入同步請求隊列中之后,同樣調用的是Response result = getResponseWithInterceptorChain()。明白了嗎,不論是在同步請求或者是異步請求,最終獲取網(wǎng)絡數(shù)據(jù)的核心處理都是一致的:getResponseWithInterceptorChain() 。
接下來我們來分析這個在OkHttp中非常核心的方法:
Response getResponseWithInterceptorChain() throws IOException {
//創(chuàng)建存放攔截器的list
List<Interceptor> interceptors = new ArrayList<>();
//攔截器列表加入我們配置OkHttpClient時添加的攔截器
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) {
//如果不是針對WebSocket的網(wǎng)絡訪問,加入網(wǎng)絡攔截器
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
//創(chuàng)建攔截器鏈
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
//執(zhí)行攔截器鏈
return chain.proceed(originalRequest);
}
在這個方法中首先創(chuàng)建了一個ArrayList,用來存放所有的攔截器。從上到下可以看到,一共是添加了7中不同的攔截器:
- client.interceptors() -> 我們自己添加的請求攔截器,通常是做一些添加統(tǒng)一的token之類操作
- retryAndFollowUpInterceptor -> 主要負責錯誤重試和請求重定向
- BridgeInterceptor -> 負責添加網(wǎng)絡請求相關的必要的一些請求頭,比如Content-Type、Content-Length、Transfer-Encoding、User-Agent等等
- CacheInterceptor -> 負責處理緩存相關操作
- ConnectInterceptor -> 負責與服務器進行連接的操作
- networkInterceptors -> 同樣是我們可以添加的攔截器的一種,它與client.interceptors() 不同的是二者攔截的位置不一樣。
- CallServerInterceptor -> 在這個攔截器中才會進行真實的網(wǎng)絡請求
在添加完各種攔截器后,創(chuàng)建了一個攔截器鏈,然后執(zhí)行了攔截器鏈的proceed方法,我們來看一下這個proceed方法:
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}
這個方法調用的是 RealInterceptorChain 內部的另一個proceed方法,再跟進去看一下:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
//忽略無關代碼......
// 獲取攔截鏈中的下一個攔截器
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
//通過調用攔截器的intercept方法獲取網(wǎng)絡數(shù)據(jù)
Response response = interceptor.intercept(next);
//忽略無關代碼......
return response;
}
這個方法中主要分為兩步:獲取攔截鏈中的下一個攔截器,然后調用這個攔截器的 intercept(next) 方法,在構建OkHttpClietn時添加過interceptor的同學應該都比較清楚,在intercept()方法中我們必須要存在chain.proceed(request)這樣一句代碼。類似于這樣:
OkHttpClient.Builder().connectTimeout(
DEFAULT_MILLISECONDS, TimeUnit.SECONDS).readTimeout(
DEFAULT_MILLISECONDS, TimeUnit.SECONDS).addInterceptor { chain ->
val builder = chain.request().newBuilder()
headerMap?.forEach {
builder.addHeader(it.key, it.value)
}
val request = builder.build()
//將攔截器鏈執(zhí)行下去
chain.proceed(request)
}.addInterceptor(httpLoggingInterceptor).build()
每個攔截器內部的intercept方法內部必須存在chain.proceed(request),同樣,OkHttp提供的攔截器的intercept方法內部都必須存在chain.proceed(request)這句代碼,除了最后一個攔截器CallServerInterceptor。
整個邏輯是不是有些混亂,沒關系,我們來整理一下。
- getResponseWithInterceptorChain()方法通過調用chain.proceed(originalRequest)開啟攔截鏈。
- 在RealInterceptorChain的proceed(request)方法中會調用下一個攔截器中的intercept(chain)方法
- 在攔截器中的intercept(chain)中會調用chain.proceed(request)
上面是一個循環(huán)調用,由于每次獲取的攔截器是攔截器列表中的下一個攔截器,所以實現(xiàn)了順序調用攔截器列表中的每個不同的攔截器的攔截方法。因為最后一個攔截器并沒有調用chain.proceed(request),所以能夠結束循環(huán)調用。
再來張圖,加深大家對攔截器鏈的理解:

看完這張圖,小伙伴們應該會對整個攔截器鏈的運作流程有一定的了解。到此為止,OkHttp的源碼分析就告一段落了,具體每個攔截器中的實現(xiàn)細節(jié),大家如果有興趣的話可以自己去深入了解一下,我這里就不再贅述了。