OkHttp 完整指南:Java 基本用法、連線池與 Timeout、TLS 設定與常見錯誤排解

這篇整理我在專案中使用 OkHttp 的完整筆記:Maven 設定、同步 / 非同步 GET 與 POST、連線池和 Dispatcher 的設定、四種 Timeout 的差別(尤其是常被忽略的 callTimeout)、TLS 與 CLEARTEXT 設定,以及實際遇過的錯誤:IllegalStateException: closed、connection was leaked、CLEARTEXT communication not enabled、unexpected end of stream,還有升級 4.12.0 後 Tomcat thread pool 爆滿的案例。

OkHttp 是什麼

OkHttp 是 Square 開發的 HTTP client,預設就很有效率:

  • HTTP/2:對同一個 host 的所有請求共用一條 socket
  • 連線池:沒有 HTTP/2 時,透過重用連線降低延遲
  • 透明的 GZIP:自動壓縮,減少下載量
  • 回應快取:重複的請求可以完全不經過網路

API 採用 fluent builder 和不可變物件設計,同時支援同步阻塞呼叫和非同步 callback 呼叫。

需求:Java 8 以上(Android 5.0 / API 21 以上),依賴 Okio 和 Kotlin 標準函式庫。官方強烈建議持續更新版本,因為 TLS 生態一直在變,HTTP client 保持最新是重要的安全防線。

Maven 設定

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>

基本用法

OkHttpClient 內含連線池和執行緒池,整個應用程式應該共用同一個實例,不要每次請求都 new 一個。

同步 GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private final OkHttpClient client = new OkHttpClient();

public void synchronousGet() throws IOException {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}

非同步 GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void asynchronousGet() {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(responseBody.string());
}
}
});
}

POST JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

public String postJson(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();

try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}

POST Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void postForm() throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}

連線池、Dispatcher 與 Timeout 設定

以下是我們專案中初始化 OkHttpClient 的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
OkHttpClient.Builder builder = new OkHttpClient.Builder();

// 連線池:最多保留 10 條閒置連線,閒置超過 6 秒就關閉
builder.connectionPool(new ConnectionPool(10, 6, TimeUnit.SECONDS));

// 四種 timeout,下一節說明差別
builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
builder.readTimeout(SOCKET_HOLD_TIMEOUT, TimeUnit.MILLISECONDS);
builder.writeTimeout(SOCKET_HOLD_TIMEOUT, TimeUnit.MILLISECONDS);
builder.callTimeout(CALL_TIMEOUT, TimeUnit.MILLISECONDS);

// 重試由程式自己精準控制,不讓 OkHttp 自動重試
builder.retryOnConnectionFailure(false);

// Dispatcher 控制「非同步」請求的併發數
Dispatcher dispatcher = new Dispatcher(executorService);
dispatcher.setMaxRequests(MAX_TOTAL); // 同時最多幾個請求
dispatcher.setMaxRequestsPerHost(MAX_PER_ROUTE); // 對同一個 host 最多幾個請求
builder.dispatcher(dispatcher);

OkHttpClient client = builder.build();

注意:Dispatcher 的上限只對 enqueue() 的非同步請求有效;同步的 execute() 是在呼叫端自己的執行緒上跑,不受它限制。

四種 Timeout 的差別

設定涵蓋範圍預設值
connectTimeout建立 TCP / TLS 連線10 秒
readTimeout兩次讀取資料之間的間隔10 秒
writeTimeout兩次寫入資料之間的間隔10 秒
callTimeout整個呼叫:DNS 查詢、連線、送出 request body、伺服器處理、讀完 response body,包含所有重新導向和重試0(不限制)

readTimeout 和 writeTimeout 算的是「兩次讀寫之間」的間隔,只要對方持續一點一點地送資料,就永遠不會觸發。callTimeout 才是整個請求的總時間上限,而它預設是關閉的。

實際案例:unexpected end of stream 與 callTimeout

我們只設定了 connectTimeout、readTimeout、writeTimeout,某次對方回應:

1
java.io.IOException: unexpected end of stream on {對方 domain}

推測是被對方的 CDN 誤判成有問題的來源,連線被故意掛著不斷線,而且這種狀況不會觸發 connect / read / write 這三種 timeout。結果 HTTP 請求一直不結束,持續佔用執行緒。

解法是設定 callTimeout,替整個請求設一個總時間上限,避免單一請求無限期佔住執行緒。實務上建議一定要設定 callTimeout。

TLS 與 CLEARTEXT 設定

指定 TLS 版本與 Cipher Suites

需要連線到只支援特定 TLS 版本的舊系統時,可以自訂 ConnectionSpec:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
.supportsTlsExtensions(true)
.tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
.build();

client = builder.connectionSpecs(Collections.singletonList(spec)).build();

當時的環境需要這樣設定才能用 TLS 1.2 連線。幾點補充:

  • 新版 OkHttp 的預設設定(MODERN_TLS)已經包含 TLS 1.2 和 TLS 1.3,一般情況不需要自訂。只有連線到舊系統、或執行環境較舊時才需要。
  • 原本的設定還包含 RC4 的 cipher suites,RC4 已被證實不安全,主流瀏覽器和 JDK 都已停用,上面的範例已經拿掉。
  • TLS 1.0 / 1.1 同樣已被淘汰,對方支援的話,建議只開 TLS 1.2 以上。

CLEARTEXT communication not enabled for client

設定了上面的 ConnectionSpec 之後,改連 http://(非 HTTPS)的網址時出現:

1
java.net.UnknownServiceException: CLEARTEXT communication not enabled for client

原因是 OkHttp 預設的 connection specs 是 MODERN_TLS 加上 CLEARTEXT。用 connectionSpecs(...) 自訂時會整個取代預設值,只放了自己的 TLS spec,就等於關掉了明文 HTTP。

解法是把 CLEARTEXT 也加回去:

1
2
3
4
5
6
7
// 解決前
client = builder.connectionSpecs(Collections.singletonList(spec)).build();

// 解決後
client = builder.connectionSpecs(Arrays.asList(
spec, ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT))
.build();

略過 SSL 憑證驗證(僅限測試環境)

測試環境常遇到自簽憑證,可以讓 client 接受所有憑證並略過 hostname 驗證:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 接受所有憑證,不做任何驗證
private final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}};

// 略過 hostname 驗證,避免請求的網域和憑證不一致時出錯
private final HostnameVerifier hostnameVerifier = (hostname, session) -> true;

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier(hostnameVerifier);

⚠️ 這等於完全關閉 HTTPS 的安全保護,任何人都能做中間人攻擊。只能用在測試環境,正式環境應該把對方的憑證或 CA 加進 truststore。

常見錯誤排解

java.lang.IllegalStateException: closed

情境:同一個 response 呼叫了兩次以上 response.body().string()。

原因:response body 是一次性的串流,string() 會把內容讀完並關閉串流,第二次讀取時串流已經關了。

解法:只讀一次,存到變數裡重複使用:

1
String body = response.body().string();

A connection to https://xxx was leaked. Did you forget to close a response body?

情境:call.execute() 之後沒有關閉 response,例如發生錯誤時提早 return 或丟出例外,OkHttp 會印出警告:

1
2
okhttp3.internal.platform.Platform log
WARNING: A connection to https://xxx was leaked. Did you forget to close a response body?

原因:沒關閉的 response 會讓連線無法回到連線池,久了會耗盡連線。

解法:不管成功或失敗都要關閉 response。最簡單的方式是 try-with-resources:

1
2
3
try (Response response = client.newCall(request).execute()) {
...
}

舊的寫法是在 finally 裡關閉:

1
2
3
4
5
6
7
8
9
Response response = null;
try {
response = client.newCall(request).execute();
...
} finally {
if (response != null) {
response.close();
}
}

升級 4.12.0 後 Tomcat thread pool 衝到上限

情境:OkHttp 從 4.10.0 升級到 4.12.0 後,高流量的機器大約 4~5 小時後,Tomcat thread pool 會衝到設定上限,造成系統異常;只有一半流量的機器則完全沒事。

分析:追了 OkHttp 底層的程式碼,發現 PING 這個動作是開 Virtual Thread 執行,而我們的 Tomcat 當時設定成使用 Virtual Threads 的 executor(tomcatThreadPoolVirtual)。

解法:把 Tomcat server.xml 改回一般的 thread pool 模式,就不再發生 thread pool 瞬間衝高的問題:

1
2
3
4
5
6
7
<Executor name="tomcatThreadPool"
...
... />

<Connector executor="tomcatThreadPool"
...
... />

檢查清單

  • 整個應用程式共用同一個 OkHttpClient?
  • 每個 Response 都有關閉(try-with-resources)?
  • response.body().string() 只呼叫一次?
  • 有設定 callTimeout,不只 connect / read / write timeout?
  • 自訂 connectionSpecs 時,需要 HTTP 的話有加 CLEARTEXT?
  • 沒有使用 RC4 之類不安全的 cipher,TLS 版本盡量 1.2 以上?
  • 略過憑證驗證的程式碼只存在測試環境?
  • 升級 OkHttp 版本後,在高流量環境觀察 thread pool 和連線數?