[HTTP] API Timeout 指南 (connect / read timeout)

Intro

關於 API Timeout 的網路資料略顯不足,Wikipedia 目前也只有廣義 Timeout (computing) 資訊。

本篇將分享個人對 Timeout 的所知,如有錯誤歡迎告知修正


Timeout 定義

Client Connect Timeout Read Timeout
TCP Client TCP handshake 中從發出 SYN 後,
至等待收到 SYN-ACK 的時間
送出 PSH-ACK packet,
至等待收到對應 PSH-ACK packet 的時間
HTTP Client TCP handshake 中從發出 SYN 後,
至等待收到 SYN-ACK 的時間
送出最後 HTTP request packet,
至等待收到最後 response packet 的時間
HTTPS Client TCP handshake 中從發出 SYN 後,
至等待收到最後 TLS handshake 的時間
送出最後 HTTP request packet,
至等待收到最後 response packet 的時間
  • API timeout = Max timeout = Connect timeout + Read timeout

Programing

Curl

// connect timeout = 5, max timeout (connect+read) = 25
$ curl -v --connect-timeout 5 -m 25 "https://yourname.com"

// Result within connection timeout
curl: (28) Connection timed out after 5004 milliseconds
// Result within read timeout
curl: (28) Operation timed out after 25005 milliseconds with 0 bytes received

CURL - Timeouts · Everything curl

Python

import requests

connect_timeout = 5; read_timeout = 20
try:
    response = requests.get("https://your.name", allow_redirects=False, timeout=(connect_timeout, read_timeout))
except requests.exceptions.ConnectTimeout:
    print("Connection Timeout")
except requests.exceptions.ReadTimeout:
    print("Read Timeout")

PHP with Guzzle

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

$client = new Client();

try {
    $response = $client->request('GET', 'https://your.name/', [
        'connect_timeout' => 5, // Connect timeout in seconds
        'timeout' => 25,        // Total (Connect + read) timeout in seconds
    ]);
} catch (ConnectException $e) {
    // A timeout occurred due to a connection or read timeout.
    echo "API Timeout";
} 

JAVA with Apache HttpClient

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ConnectTimeoutException;
import java.net.SocketTimeoutException;
import java.io.IOException;

public class ApacheHttpClient {
    public static void main(String[] args) {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(5000)    // Connect timeout
                .setSocketTimeout(20000)    // Read timeout
                .build();
        try (final CloseableHttpClient httpclient =
                     HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
            final HttpGet httpget = new HttpGet("https://your.name");
            CloseableHttpResponse response = httpclient.execute(httpget);
        } catch (ConnectTimeoutException e) {
            // Handle connect timeout
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            // Handle read timeout
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

References

Leave a Reply

Your email address will not be published. Required fields are marked *