HttpClient 4.3.5 ConnectionRequestTimeOut与ConnectTimeout for 4.0中的HttpConnectionParams.setConnectionTimeout

时间:2015-01-02 23:23:41

标签: apache-httpclient-4.x

我正在尝试将HttpClient依赖关系从4.0.1升级到4.3.5。并且在新lib中设置连接超时时感到困惑。对于以下代码:

HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 300);

它将替换为以下代码:

RequestConfig config = RequestConfig.custom().setConnectTimeout(300).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

但是,我不确定是否应该使用 setConnectTimeout setConnectionRequestTimeout ,因为我不熟悉HttpClient。在我看来,我应该使用基于源代码中的java doc的 setConnectionTimeout 。有人可以确认一下吗?提前谢谢。

https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.3.3/httpclient/src/main/java/org/apache/http/client/config/RequestConfig.java

/**
 * 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/>
 * Default: <code>-1</code>
 */
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/>
 * Default: <code>-1</code>
 */
public int getConnectTimeout() {
    return connectTimeout;
}

2 个答案:

答案 0 :(得分:14)

在Apache Http Client的4.3版中,配置被重构(再次)。 新方法如下代码:

RequestConfig requestConfig =RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout).build();

连接超时是指在建立与服务器的连接之前的超时。 从连接管理器请求连接时使用的ConnectionRequestTimeout。

答案 1 :(得分:3)

Apache HttpClient中三个超时之间的区别:

connectTimeout与远程主机/服务器建立连接的最长时间。

connectionRequestTimeout时间等待从连接管理器/池获得连接。 (HttpClient维护一个连接池来管理连接。类似于数据库连接池)

socketTimeout在从服务器到客户端传输数据的两个连续数据包之间的最大时间间隔。