I am trying to upgrade our HttpClient Dependency from 4.0.1 to 4.3.5. And was confused on setting the connection timeout in the new lib. For the following code:
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 300);
It will be replaced with the code below:
RequestConfig config = RequestConfig.custom().setConnectTimeout(300).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
However, I am not sure if I should use setConnectTimeout or setConnectionRequestTimeout since I am not familiar with HttpClient. It seems to me I should use setConnectionTimeout based on the java doc in the source code. Can somebody please confirm? Thanks in advance.
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;
}
In version 4.3 of Apache Http Client the configuration was refactored (again). the new way as the following code:
RequestConfig requestConfig =RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout).build();
connectTimeout
is the timeout until a connection with the server is established. connectionRequestTimeout
is used when requesting a connection from the connection manager.
Difference between the three timeouts in Apache HttpClient :
connectTimeout
max time to establish a connection with remote host/server.
connectionRequestTimeout
time to wait for getting a connection from the connection manager/pool. (HttpClient maintains a connection pool to manage the connections. Similar to database connection pool)
socketTimeout
max time gap between two consecutive data packets while transferring data from server to client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With