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

OkHttp 源碼全解析:從設計思想到請求流程的深度剖析

編輯:關於 Android 開發

原文來源:https://frodoking.github.io/2015/03/12/android-okhttp/

在 Android 平台上,官方為我們準備了兩套與伺服器通信的方案:HttpURLConnection 與 Apache HTTP Client。這兩者都支援 HTTPS、串流式的上傳下載、超時設定、IPv6 以及連線池,基本能應付日常絕大多數的網路請求場景。然而,若能以更高的效率去使用 HTTP,應用的運行會更順暢、流量也更省。OkHttp 正是為這個目標而誕生的高效 HTTP 庫。

OkHttp 的核心優勢

作為一款現代化的 HTTP 客戶端,OkHttp 具備以下幾個亮點:

  • 支援 SPDY 協議,能透過共用同一個 Socket 來處理發往同一伺服器的所有請求;
  • 當 SPDY 不可用時,則借助連線池機制降低請求延遲;
  • 無縫整合 GZIP 壓縮,有效減少資料傳輸量;
  • 透過快取回應資料,避免重複的網路請求。

更值得一提的是它的容錯能力。當伺服器配置了多個 IP 位址時,若第一個 IP 連線失敗,OkHttp 會自動改用下一個位址重試;此外它還能妥善處理代理伺服器以及 SSL 握手失敗等常見問題。

遷移成本同樣友好。OkHttp 幾乎完整實作了與 java.net.HttpURLConnection 一致的 API,因此無需大改既有的網路程式碼;如果你原本使用 Apache HttpClient,也能直接換用官方提供的 okhttp-apache 模組。

原始碼位址:https://github.com/square/okhttp

快速上手

下面是一段最基礎的同步請求範例:

  1. private final OkHttpClient client = new OkHttpClient();
  2. public void run() throws Exception {
  3.     Request request = new Request.Builder()
  4.         .url("https://api.github.com/repos/square/okhttp/issues")
  5.         .header("User-Agent", "OkHttp Headers.java")
  6.         .addHeader("Accept", "application/json; q=0.5")
  7.         .addHeader("Accept", "application/vnd.github.v3+json")
  8.         .build();
  9.     Response response = client.newCall(request).execute();
  10.     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  11.     System.out.println("Server: " + response.header("Server"));
  12.     System.out.println("Date: " + response.header("Date"));
  13.     System.out.println("Vary: " + response.headers("Vary"));
  14. }

這裡不展開講解具體用法,接下來我們把重點放到原始碼的分析上。

整體架構設計

上圖展示了 OkHttp 的總體結構。整個框架由 Dispatcher 不斷從請求佇列中取出請求(Call),再根據是否命中快取,決定調用 Cache 或 Network 這兩類資料獲取介面之一,最終從記憶體快取或伺服器取得資料。引擎同時支援同步與異步兩種模式:同步請求透過 Call.execute() 直接回傳 Response;異步請求則把 Call.enqueue 封裝為 AsyncCall 加入佇列,並透過 Callback 回呼取得最終結果。

接下來將介紹幾個關鍵類別。至於底層 IO 相關的實作,主要來自 okio 這個套件。出於準確性考量,部分類別說明保留英文原文,以免翻譯失真。

OkHttp 中的關鍵類別

1. Route.java
The concrete route used by a connection to reach an abstract origin server. When creating a connection the client has many options:

  • HTTP proxy: a proxy server may be explicitly configured for the client. Otherwise the proxy selector is used. It may return multiple proxies to attempt.
  • IP address: whether connecting directly to an origin server or a proxy, opening a socket requires an IP address. The DNS server may return multiple IP addresses to attempt.
  • TLS configuration: which cipher suites and TLS versions to attempt with the HTTPS connection.

Each route is a specific selection of these options. 簡單說,它就是對連線位址的封裝類,地位卻相當關鍵。

2. Platform.java
Access to platform-specific features.

  • Server name indication (SNI): Supported on Android 2.3+.
  • Session Tickets: Supported on Android 2.3+.
  • Android Traffic Stats (Socket Tagging): Supported on Android 4.0+.
  • ALPN (Application Layer Protocol Negotiation): Supported on Android 5.0+.

這個類負責平台適配,針對 Android 2.3 到 5.0 各版本的網路請求能力提供支援。在類中還能看到,針對不同平台會透過 Java 反射去載入不同的 class。

3. Connection.java
The sockets and streams of an HTTP, HTTPS, or HTTPS+SPDY connection. May be used for multiple HTTP request/response exchanges. Connections may be direct to the origin server or via a proxy. Modern TLS options such as SNI and ALPN are quite useful, but older HTTPS servers may refuse to connect when such options are presented. Rather than avoiding these options entirely, this class allows a connection to be attempted with modern options and then retried without them should the attempt fail.

4. ConnectionPool.java
Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP requests that share the same Address may share a Connection. The system-wide default uses system properties for tuning parameters:

  • http.keepAlive: true if HTTP and SPDY connections should be pooled at all. Default is true.
  • http.maxConnections: maximum number of idle connections to keep in the pool. Default is 5.
  • http.keepAliveDuration: Time in milliseconds to keep the connection alive before closing it. Default is 5 minutes.

5. Request.java
An HTTP request. Instances of this class are immutable if their body is null or itself immutable.(採用 Builder 模式)

6. Response.java
An HTTP response. Instances of this class are not immutable: the response body is a one-shot value that may be consumed only once. All other properties are immutable.

7. Call.java
A call is a request that has been prepared for execution. A call can be canceled. As this object represents a single request/response pair (stream), it cannot be executed twice.

8. Dispatcher.java
Policy on when async requests are executed. Each dispatcher uses an ExecutorService to run calls internally.

9. HttpEngine.java
Handles a single HTTP request/response pair. Each HTTP engine follows this lifecycle: it is created; the request message is sent with sendRequest(); the response message is read with readResponse(). The request and response may be served by the cache, by the network, or by both in the event of a conditional GET.

10. Internal.java
Escalate internal APIs in com.squareup.okhttp so they can be used from OkHttp's implementation packages.

11. Cache.java
Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth. To measure cache effectiveness, this class tracks three statistics: Request Count, Network Count, and Hit Count. Sometimes a request results in a conditional cache hit, which increments both the network count and hit count.

Force a Network Response — 若要在使用者點擊「重新整理」後跳过快取,可加入 no-cache 指令:

  1. connection.addRequestProperty("Cache-Control", "no-cache")

若只需讓伺服器驗證快取是否有效,用更省資源的 max-age=0 即可:

  1. connection.addRequestProperty("Cache-Control", "max-age=0");

Force a Cache Response — 若希望僅使用本地快取資源,可加入 only-if-cached 指令;配合 max-stale 還能容忍過期回應:

  1. int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
  2. connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);

12. OkHttpClient.java
Configures and creates HTTP connections. Most applications can use a single OkHttpClient for all of their HTTP requests, benefiting from a shared response cache, thread pool, connection re-use, etc. Instances are intended to be fully configured before they're shared; once shared they should be treated as immutable.

請求流程圖

下圖呈現了 OkHttp 的請求流程:

核心類別關係圖

由於整體類圖龐大,本文將從核心入口 client、cache、interceptor、網路配置、連線池、平台適配等幾個維度逐一剖析。

先看核心入口 OkHttpClient 的類設計圖:

從整體設計來看,OkHttpClient 採用了典型的門面模式(Facade)。client 掌握著所有子模組的配置,並負責提供所需參數,再將來自客戶端的請求委派給相應子系統去處理。這些子系統包含快取、連線與連線池相關類別的集合、網路配置相關類別的集合等等。子系統本身並不知道門面的存在,對它們而言,門面也不過是另一個客戶端而已。同時,OkHttpClient 幾乎扮演了整個框架的上下文角色。

透過類圖可以清楚看到框架的幾大核心子系統:路由、連線協議、攔截器、代理、安全性認證、連線池以及網路適配。門面模式的引入大幅降低了開發者的使用門檻,也讓整個框架的配置與結果獲取方式一目了然。

同步與異步的實作

發起請求時,框架主要透過 Call 來封裝每一次請求,而 Call 持有 OkHttpClient 與一份 HttpEngine。無論同步還是異步,都離不開 Dispatcher 的參與,兩者的差別在於:

  • 同步:Dispatcher 會在同步執行佇列中記錄當前被執行的 Call,並在目前執行緒中直接調用 getResponseWithInterceptorChain() 取得 Response;
  • 異步:Dispatcher 內部實作了一個懶加載、無邊界限制的執行緒池,並採用 SynchronousQueue 這種阻塞佇列。SynchronousQueue 的每次插入都必須等待另一執行緒的移除,反之亦然,因此其內部實際上容量為 0。這種設計讓元素總能以最快速度從生產者傳遞給消費者,特別適合高頻請求場景。異步執行透過 Call.enqueue(Callback) 完成,Dispatcher 會把封裝了 Callback 的匿名內部類 AsyncCall 加入執行。AsyncCall 的 execute 方法最終仍會回呼到 getResponseWithInterceptorChain 完成請求,並透過 Callback 回傳結果或狀態。

接著來看 Call 的 getResponseWithInterceptorChain() 方法,這裡的重點是攔截器鏈條的實作與作用。

攔截器究竟有何用處

先來看 Interceptor 的官方說明:觀察、修改,並可能短路請求的輸出與回應。通常攔截器用於添加、移除或轉換請求/回應的標頭。其介面中的 intercept(Chain chain) 方法會回傳 Response,整體設計頗有 AOP 面向切面編程的意味。下面用原始碼中的範例來說明:

  1. public final class LoggingInterceptors {
  2.     private static final Logger logger = Logger.getLogger(LoggingInterceptors.class.getName());
  3.     private final OkHttpClient client = new OkHttpClient();
  4.     public LoggingInterceptors() {
  5.         client.networkInterceptors().add(new Interceptor() {
  6.                 @Override public Response intercept(Chain chain) throws IOException {
  7.                      long t1 = System.nanoTime();
  8.                      Request request = chain.request();
  9.                      logger.info(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
  10.                      Response response = chain.proceed(request);
  11.                      long t2 = System.nanoTime();
  12.                      logger.info(String.format("Received response for %s in %.1fms%n%s", request.url(), (t2 - t1) / 1e6d, response.headers()));
  13.                      return response;
  14.                 }
  15.             });
  16.     }
  17.     public void run() throws Exception {
  18.         Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build();
  19.         Response response = client.newCall(request).execute();
  20.         response.body().close();
  21.     }
  22. }

執行後可以看到攔截器會記錄請求與回應的標頭資訊,包括 Host、Connection、Accept-Encoding、伺服器類型、回應耗時等。從執行結果不難看出,攔截器本質上是針對 Request 與 Response 的切面處理。

那麼原始碼究竟在哪裡完成這一切?下面是一張執行堆疊的截圖:

若你對 Interceptor 還有興趣,可以去看原始碼 simples 模組中的 GzipRequestInterceptor.java,它示範了如何對 request body 進行 gzip 壓縮。

這裡再補充一下 Call 的作用:每個 Call 都持有獨立的 HttpEngine,其中負責各種鏈路與位址的選擇,還有一個較為關鍵的 Transport。

快取策略

OkHttpClient 內部暴露了 Cache 與 InternalCache,其中 InternalCache 不應手動建立。作為開發者,一般用法如下:

  1. public final class CacheResponse {
  2.     private final OkHttpClient client;
  3.     public CacheResponse(File cacheDirectory) throws Exception {
  4.         int cacheSize = 10 * 1024 * 1024; // 10 MiB
  5.         Cache cache = new Cache(cacheDirectory, cacheSize);
  6.         client = new OkHttpClient();
  7.         client.setCache(cache);
  8.     }
  9. }

執行後可觀察到:第一次請求來自網路,第二次則命中快取,兩次回應內容一致。這說明快取機制正常運作。

接下來說明整個框架的快取策略是如何實現的,重點落在 Call.getResponse() 中的 Engine.sendRequest() 與 Engine.readResponse() 兩個環節。

sendRequest() 會先對可能的 Response 資源進行預判,必要時開啟 socket。它會透過 Internal.instance.internalCache(client) 取得快取,並在快取初始化時讀取目錄中曾請求過的所有資訊,最後封裝 CacheStrategy 決定使用網路還是快取。

  1. public void sendRequest() throws IOException {
  2.     if (cacheStrategy != null) return; // Already sent.
  3.     Request request = networkRequest(userRequest);
  4.     InternalCache responseCache = Internal.instance.internalCache(client);
  5.     Response cacheCandidate = responseCache != null ? responseCache.get(request) : null;
  6.     long now = System.currentTimeMillis();
  7.     cacheStrategy = new CacheStrategy.Factory(now, request, cacheCandidate).get();
  8.     if (networkRequest != null && connection == null) connect();
  9.     transport = Internal.instance.newTransport(connection, this);
  10. }

readResponse() 則負責發起刷新建議、解析回應標頭,並在存在回應體時讀取內容。這裡既包含把結果寫入快取,也包含拿快取與網路結果進行比對的過程。若快取可用,就採用快取 Response 並關閉網路連線、釋放資源;否則以網路回應為準並更新快取。

  1. public void readResponse() throws IOException {
  2.     Response networkResponse;
  3.     networkResponse = new NetworkInterceptorChain(0, networkRequest).proceed(networkRequest);
  4.     receiveHeaders(networkResponse.headers());
  5.     if (cacheResponse != null && validate(cacheResponse, networkResponse)) {
  6.         userResponse = cacheResponse.newBuilder()...build();
  7.         releaseConnection();
  8.         responseCache.trackConditionalCacheHit();
  9.     }
  10.     if (hasBody(userResponse)) { maybeCache(); }
  11. }

HTTP 連線的實作方式(連線池)

所有外部網路請求的入口都透過 Transport 介面完成,它以橋接模式把 HttpEngine 與 HttpConnection 串接起來。HttpEngine 只是邏輯處理器,同時充當請求配置的提供引擎;HttpConnection 則是對底層連線的封裝。

作為一個負責傳送 HTTP/1.1 訊息的 socket 連線,HttpConnection 的生命週期大致如下:

1、發送請求標頭;
2、開啟一個 sink(固定長度或 chunked 塊結構)以寫入請求 body;
3、寫入並關閉 sink;
4、讀取 Response 標頭;
5、開啟一個 source 讀取 Response body;
6、讀取並關閉 source;

下面這張時序圖描繪了連線執行的過程:

補充幾點關於連線池的細節:

1、連線池暴露在 client 之下,貫穿了 Transport、HttpEngine、Connection、HttpConnection 與 SpdyConnection;
2、ConnectionPool 有兩個建構參數:maxIdleConnections(最大空閒連線數)與 keepAliveDurationNs(存活時間),並預設採用單執行緒的清理機制;
3、請求實際在 HttpConnection.flush() 處刷入,此處需特別關注 sink 與 source,它們都依托同一個 socket 建立,底層最終對應到 socket 的輸入輸出串流。

重連機制

這一節著重說明自動重連是如何實現的,先來看時序圖:

回到 Call.getResponse() 方法:

  1. Response getResponse(Request request, boolean forWebSocket) throws IOException {
  2.     while (true) { // 自動重連機制的循環處理
  3.         if (canceled) { engine.releaseConnection(); return null; }
  4.         try {
  5.             engine.sendRequest();
  6.             engine.readResponse();
  7.         } catch (IOException e) {
  8.             HttpEngine retryEngine = engine.recover(e, null);
  9.             if (retryEngine != null) { engine = retryEngine; continue; }
  10.             throw e; // 無法恢復則中斷
  11.         }
  12.         Response response = engine.getResponse();
  13.     }
  14. }

這段程式碼清楚呈現了自動重連的實現思路,具體步驟如下:

1、HttpEngine.recover() 會檢測 RouteSelector 是否還有更多 route 可嘗試,並判斷是否可以恢復,若可以則建立一份新的 HttpEngine 並帶入相應鏈路資訊;
2、當恢復後的 HttpEngine 不為空,就替換當前 Call 中的 HttpEngine,執行 continue 發起下一次請求;
3、sendRequest() 會觸發 connect(),其中透過 RouteSelector.next() 尋找合適的 Route,並最終呼叫 InetAddress.getAllByName(host) 完成位址解析,因此可支援多個位址的組態。

Gzip 的使用方式

在原始碼範例 RequestBodyCompression.java 中可以看到 gzip 的身影,它透過攔截器對 Request body 進行 gzip 壓縮以減少流量。其實現主要是以 GzipSink 對普通 sink 進行封裝壓縮,有興趣的讀者可對照原始碼研究。強大的 Interceptor 設計,可以說是這個框架的一大亮點。

安全性

連線安全性主要體現在 HttpEngine.connect() 方法。其中靜態方法 createAddress(client, networkRequest) 會取得 OkHttpClient 關於 SSLSocketFactory、HostnameVerifier 與 CertificatePinner 的配置資訊,這些資訊大多採用預設值,並會在後續重連時作為比對參考。而在 Connection.upgradeToTls() 方法中,則負責 SSLSocket、SSLSocketFactory 的建立,這些都會記錄到 ConnectionSpec 中,並在 apply() 時觸發一系列配置與驗證。建議先了解 Java 的 SSLSocket 開發,再來理解框架的安全性設計會更順暢。

平台適配性

Platform 是整個平台適配的核心類,它封裝了针对不同平台的 Android 與 JdkWithJettyBootPlatform 等類別,實作位於 Platform.findPlatform 中。

  1. private static Platform findPlatform() {
  2.     try {
  3.         try {
  4.             Class.forName("com.android.org.conscrypt.OpenSSLSocketImpl");
  5.         } catch (ClassNotFoundException e) {
  6.             Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl");
  7.         }
  8.         // 嘗試偵測 Android 4.0+ / 5.0+ 的 API
  9.         return new Android(...);
  10.     } catch (ClassNotFoundException ignored) {
  11.         // 非 Android 執行環境,嘗試 Jetty ALPN 擴充
  12.     }
  13.     return new Platform();
  14. }

這裡採用 Java 反射原理去呼叫 class 的 method,最後在各自平台上透過 invoke 執行相應方法。要完成這些適配,前提是必須知道當前平台在記憶體中的相關 class 位址與方法。詳情可參考繼承自 Platform 的 Android 類。

總結

1、從整體結構與類內部域不難看出,OkHttpClient 有點類似於 Android 的 ApplicationContext,更像一個單例類,統一管理的用好處是清晰一致,但邏輯牽連較深,除錯時需謹慎;
2、框架中的動態方法、靜態方法、匿名內部類以及 Internal 的程式碼相當規整,不同類的不同職責劃分得很清楚,非常值得學習;
3、從平台兼容性來看,也是相當出色的典範,若日後從事 API 相關開發更應注意兼容性處理;
4、由於篇幅與時間有限,對部分細節的掌握仍不夠深入,這方面還需多加努力;
5、對於初學網路編程的同學而言,往往從簡單的 socket 請求開始,這是許多剛入行者共同的成長痛點;
6、不足之处在於未對 SPDY 方式做最詳盡的剖析,後續若有機會再補上。

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