Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

OkHttp 源碼完全解析:從 Request 到連接池

編輯:關於 Android 程式設計

OkHttp 是目前 Android 上最受歡迎的網路庫之一。本文將帶你深入源碼,理清 OkHttp 的核心架構:如何從構造 Request、初始化 OkHttpClient 到產生 Call,如何執行同步與異步請求,以及攔截器、連接池、StreamAllocation、HttpEngine 等關鍵角色如何協同運作。

核心概念速覽

  • 外部透過構造 Request、初始化 OkHttpClient,兩者共同構造出 Call。
  • 網路訪問透過 Call 完成,支援同步(execute,立即返回 Response)與異步(enqueue,透過 callback 接收結果)兩種模式。
  • OkHttp 支援攔截器,分為「請求前攔截」與「網絡返回前攔截」兩種。
  • 支援 host 檢查、證書檢查,以及 HTTP/1.0、1.1、2.0、SPDY 等協議。

先給一張關係圖(建議放大查看):

RealCall 與攔截器鏈

OkHttpClient.newCall() 回傳的是 RealCall:

@Override public Call newCall(Request request) {
    return new RealCall(this, request);
}

RealCall 記錄了傳入的 request 以及 HttpEngine(可理解為網路訪問的入口)。同步執行的 execute:

@Override public Response execute() throws IOException {
    synchronized (this) {
        if (executed) throw new IllegalStateException("Already Executed");
        executed = true;
    }
    try {
        client.dispatcher().executed(this);
        Response result = getResponseWithInterceptorChain(false);
        if (result == null) throw new IOException("Canceled");
        return result;
    } finally {
        client.dispatcher().finished(this);
    }
}

核心在於 getResponseWithInterceptorChain(false),它建立一條攔截器鏈來處理請求:

private Response getResponseWithInterceptorChain(boolean forWebSocket) throws IOException {
    Interceptor.Chain chain = new ApplicationInterceptorChain(0, originalRequest, forWebSocket);
    return chain.proceed(originalRequest);
}

Interceptor 與 Chain 的介面非常簡潔:

public interface Interceptor {
    Response intercept(Chain chain) throws IOException;
    interface Chain {
        Request request();
        Response proceed(Request request) throws IOException;
        Connection connection();
    }
}

Chain 的作用,就是讓 request 依序經歷每個攔截器的 intercept 方法。ApplicationInterceptorChain 的 proceed 會遍歷 client 中的所有攔截器:

@Override public Response proceed(Request request) throws IOException {
    if (index < client.interceptors().size()) {
        Interceptor.Chain chain = new ApplicationInterceptorChain(index + 1, request, forWebSocket);
        Interceptor interceptor = client.interceptors().get(index);
        Response interceptedResponse = interceptor.intercept(chain);
        if (interceptedResponse == null) {
            throw new NullPointerException("application interceptor returned null");
        }
        return interceptedResponse;
    }
    return getResponse(request, forWebSocket);
}

getResponse:訪問網絡的核心循環

走完所有攔截器後,便進入 getResponse。它先根據 request 的參數重建一個帶有 Content-Type、Content-Length 等標頭的 request,然後建立 HttpEngine 並進入一個 while(true) 循環:

Response getResponse(Request request, boolean forWebSocket) throws IOException {
    // ... 補全請求標頭 ...
    engine = new HttpEngine(client, request, false, false, forWebSocket, null, null, null);
    int followUpCount = 0;
    while (true) {
        if (canceled) { engine.releaseStreamAllocation(); throw new IOException("Canceled"); }
        try {
            engine.sendRequest();
            engine.readResponse();
        } catch (RouteException e) {
            HttpEngine retryEngine = engine.recover(e.getLastConnectException(), null);
            if (retryEngine != null) { engine = retryEngine; continue; }
            throw e.getLastConnectException();
        } catch (IOException e) {
            HttpEngine retryEngine = engine.recover(e, null);
            if (retryEngine != null) { engine = retryEngine; continue; }
            throw e;
        }
        Response response = engine.getResponse();
        Request followUp = engine.followUpRequest();
        if (followUp == null) { engine.releaseStreamAllocation(); return response; }
        // ... 處理重定向,超過 MAX_FOLLOW_UPS 則拋出異常 ...
        engine = new HttpEngine(client, followUp, false, false, forWebSocket, streamAllocation, null, response);
    }
}

循環中先呼叫 sendRequest() 發送請求,再以 readResponse() 讀取結果;若發生 RouteException 或 IOException,會嘗試 recover 重連。成功後透過 followUpRequest() 判斷是否需要重定向——重定向時 response 仍回傳 200,並在 header 中帶出下一個 url。重定向次數上限由 MAX_FOLLOW_UPS 決定。

StreamAllocation、RealConnection 與連接池

HTTP/2.0 相比 1.x 最重要的改進是「連接複用」與解決「隊列頭阻塞(HOL blocking)」:多個 stream 可共用同一條 TCP 連接,只要它們連向相同的 host 與 port,就能共享一個 socket,省去重複三次握手的開銷。

在 OkHttp 中,一次連接由 RealConnection 記錄,它負責用 socket 建立連接,並以 HandShake 處理握手。同一個 RealConnection 上可能掛著多個 stream,因此其中維護了一個 allocations 清單;而 StreamAllocation 則記錄當前這個 stream 被分配到哪個 RealConnection。每次新建的 RealConnection 都會放入 ConnectionPool,以便後續請求複用。

值得一提的是 OkHttp 與 HttpUrlConnection、Volley 的層級差異:OkHttp 與 HttpUrlConnection 同級,都是直接用 socket 實現網路連接,只是 OkHttp 更強大;而 Volley 底層仍依賴 HttpUrlConnection,只封裝了請求過程。OkHttp 在 IO 上使用 Okio 的 sink(相當於 OutputStream)與 source(相當於 InputStream),功能更強,例如 BufferedSink、GzipSink 等。

關於重定向時的連接判斷:

if (!engine.sameConnection(followUp.url())) {
    streamAllocation.release();
    streamAllocation = null;
}
public boolean sameConnection(HttpUrl followUp) {
    HttpUrl url = userRequest.url();
    return url.host().equals(followUp.host())
        && url.port() == followUp.port()
        && url.scheme().equals(followUp.scheme());
}

若重定向前後的 host、port、scheme 一致,則複用原 stream;否則釋放並重建。

HttpEngine 與緩存策略

sendRequest 中,OkHttp 會先透過 networkRequest() 把外部傳入的 userRequest 封裝成真正用於訪問網路、可被 OkHttp 修改的 networkRequest,然後取得 InternalCache 並嘗試命中緩存,最後交由 CacheStrategy 決定究竟走網路還是讀緩存:

public void sendRequest() throws RequestException, RouteException, IOException {
    if (cacheStrategy != null) return;
    Request request = networkRequest(userRequest);
    InternalCache responseCache = Internal.instance.internalCache(client);
    Response cacheCandidate = responseCache != null ? responseCache.get(request) : null;
    long now = System.currentTimeMillis();
    cacheStrategy = new CacheStrategy.Factory(now, request, cacheCandidate).get();
    networkRequest = cacheStrategy.networkRequest;
    cacheResponse = cacheStrategy.cacheResponse;
    // 若網路與緩存皆不可用,回傳 504 ...
    // 若僅需緩存,直接以 cacheResponse 構建 userResponse ...
    // 否則建立 HttpStream 進行網路訪問
    httpStream = connect();
    // ... 寫入請求標頭與 body ...
}

網路訪問由 HttpStream 介面承擔,它有兩個實作:Http2xStream(基於 FramedConnection,負責 HTTP/2.0)與 Http1xStream(基於 sink/source,負責 HTTP/1.x)。connect 最終會呼叫 streamAllocation.newStream(...),根據 RealConnection 是否含 framedConnection 決定回傳哪一種 stream。

StreamAllocation 建立 RealConnection 的順序是:先看自己是否已有連接,再向 ConnectionPool 索取,都沒有時才新建並放入池中——放入池中或已記錄在 StreamAllocation 裡的,都是「已連接」狀態。

當一個 stream 結束,需要 release 並關閉 sink、source 或 framedConnection,同時釋放 RealConnection 的 allocations 項,做好收尾。readResponse 之後還有一次「返回前攔截」,原理與請求前攔截相同。此外,Route 與 RouteDatabase 則用來記住走過的「彎路」,避免後續重複嘗試失敗的路由。

至此,OkHttpClient、RealCall、StreamAllocation、RealConnection、ConnectionPool 與 HttpEngine 這幾個核心角色的職責與協作關係便已清晰呈現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved