连接和连接请求超时

我正在使用Http Apache组件来执行http交互。我需要调整我的 http 客户端。为此,我有两个参数:连接超时和连接请求超时。在库文档和源代码中(没有找到注释),我没有找到这个术语的定义。我需要知道它们到底是什么意思。可能是它们在HTTP协议文档中定义的,但我找不到它。所以,我的问题是这两个术语是什么意思,以及它们如何彼此区别。


答案 1

HttpClient有一种方法可以根据HttpClient javadocs设置连接和套接字超时( and )。setConnectionTimeout()setTimeout()

Connection timeout是与服务器建立连接之前的超时。

Socket timeout是接收数据的超时(套接字超时)。

例:

假设您将浏览器指向某个网页。如果服务器在 X 秒内未发生异常,则会发生连接超时。但是,如果它建立了连接,则服务器将开始处理浏览器的结果。如果它没有在 Y 秒内结束此处理,则会发生套接字超时。


答案 2

从文档中:

/**
 * Returns the timeout in milliseconds used when requesting a connection
 * from the connection manager. A timeout value of zero is interpreted
 * as an infinite timeout.
 * <p>
 * A timeout value of zero is interpreted as an infinite timeout.
 * A negative value is interpreted as undefined (system default).
 * </p>
 * <p>
 * Default: {@code -1}
 * </p>
 */
public int getConnectionRequestTimeout() {
    return connectionRequestTimeout;
}

/**
 * Determines the timeout in milliseconds until a connection is established.
 * A timeout value of zero is interpreted as an infinite timeout.
 * <p>
 * A timeout value of zero is interpreted as an infinite timeout.
 * A negative value is interpreted as undefined (system default).
 * </p>
 * <p>
 * Default: {@code -1}
 * </p>
 */
public int getConnectTimeout() {
    return connectTimeout;
}

这是代码的外观:

HttpClientBuilder clientBuilder = HttpClientBuilder.create();
RequestConfig.Builder requestBuilder = RequestConfig.custom();
// Connection Timeout to establish a connection
requestBuilder = requestBuilder.setConnectTimeout(connectTimeoutMillis);
// Timeout to get a connection from the connection manager for the Http Client
requestBuilder = requestBuilder.setConnectionRequestTimeout(requestTimeoutMillis);
// Timeout between two data packets from the server
requestBuilder = requestBuilder.setSocketTimeout(requestTimeoutMillis);
clientBuilder.setDefaultRequestConfig(requestBuilder.build());
CloseableHttpClient httpClient = clientBuilder.build();

推荐