50

How do I set the connection timeout in httpcomponents httpclient? I have found the documentation at: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html but it is not clear how these parameters are actually set.

Also, an explanation of the difference between SO_TIMEOUT and CONNECTION_TIMEOUT would be helpful.

Jonik
  • 80,077
  • 70
  • 264
  • 372
Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130

5 Answers5

109

In version 4.3 of Apache Http Client the configuration was refactored (again). The new way looks like this:

RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder.setConnectTimeout(timeout);
requestBuilder.setConnectionRequestTimeout(timeout);

HttpClientBuilder builder = HttpClientBuilder.create();     
builder.setDefaultRequestConfig(requestBuilder.build());
HttpClient client = builder.build();
Leonel Sanches da Silva
  • 6,972
  • 9
  • 46
  • 66
30thh
  • 10,861
  • 6
  • 32
  • 42
  • 11
    You need to add `requestBuilder.setSocketTimeout(timeout);` too. Please note that `timeout` should be milliseconds! – Stefan Aug 29 '14 at 10:41
  • 6
    Note that calling `setConnectTimeout()` and [`setConnectionRequestTimeout()`](http://stackoverflow.com/questions/20271017/connection-and-connection-request-timeout#comment30255182_20271424) is **not** the same as setting `CONNECTION_TIMEOUT` and `SO_TIMEOUT` (as in the question). You probably want `setConnectTimeout()` and `setSocketTimeout()`. – Jonik Feb 10 '15 at 09:50
  • 7
    Also, the Builder allows you to chain those statements for much simpler code: `RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();` – Jonik Feb 10 '15 at 09:53
  • Builder objects quite often provide a fluent interface and there's nothing to hate about it. `RequestConfig.custom().setConnectionTimeout(timeout).setConnectionRequestTimeout(timeout).build()` is all it takes to build you the RequestConfig you need. Same goes for HttpClient building... – Peter Perháč Dec 23 '16 at 21:43
13

In HttpClient 4.3 version you can use below example.. let say for 5 seconds

int timeout = 5;
RequestConfig config = RequestConfig.custom()
  .setConnectTimeout(timeout * 1000)
  .setConnectionRequestTimeout(timeout * 1000)
  .setSocketTimeout(timeout * 1000).build();
CloseableHttpClient client = 
  HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpGet request = new HttpGet("http://localhost:8080/service"); // GET Request
response = client.execute(request);
MADHAIYAN M
  • 2,028
  • 25
  • 22
9

The answer from @jontro is correct, but it's always nice to have a code snippet on how to do this. There are two ways to do this:

Version 1: Set a 10 second timeout for each of these parameters:

HttpClient httpclient = new DefaultHttpClient();
// this one causes a timeout if a connection is established but there is 
// no response within 10 seconds
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10 * 1000);

// this one causes a timeout if no connection is established within 10 seconds
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 1000);

// now do the execute:
HttpGet httpget = new HttpGet(URL);
HttpResponse response = httpclient.execute(httpget);



Version 2: Also set a 10 second timeout for each of these parameters:

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
HttpConnectionParams.setSoTimeout(params, 10 * 1000);

HttpClient httpclient = new DefaultHttpClient(params);
HttpGet httpget = new HttpGet(URL);
HttpResponse response = httpclient.execute(httpget);
quux00
  • 13,679
  • 10
  • 57
  • 69
  • See also the static methods HttpConnectionParams.setConnectionTimeout() and HttpConnectionParams.setSoTimeout() which provide a slightly more convenient way to accomplish the same thing. – dnault Jan 24 '13 at 20:44
  • 1
    `.getParams()` ids deprecated now and throws a `UnsupportedOperationException` –  Dec 03 '15 at 21:44
5

In section 2.5 you see an example of how to set the CONNECTION_TIMEOUT parameter.

CONNECTION_TIMEOUT is the time waiting for the initial connection and SO_TIMEOUT is the timeout that you wait for when reading a packet after the connection is established.

jontro
  • 10,241
  • 6
  • 46
  • 71
4

I set a hard timeout for the entire request to workaround the java.net.SocketInputStream.socketRead0 problem.

private static final ScheduledExecutorService SCHEDULED_EXECUTOR = Executors.newSingleThreadScheduledExecutor()

HttpGet request = new HttpGet("http://www.example.com")
final Runnable delayedTask = new Runnable() {
    @Override
    public void run() {
        request.abort()
    }
}
SCHEDULED_EXECUTOR.schedule(delayedTask, 100000, TimeUnit.MILLISECONDS)
soulmachine
  • 3,917
  • 4
  • 46
  • 56
  • Nice pattern. Worth canceling the delayed task in case the request finished successfully or failed because of something else – Vic Aug 21 '18 at 13:29