Using Apache HttpClient how to set the TIMEOUT on a request and response Using Apache HttpClient how to set the TIMEOUT on a request and response java java

Using Apache HttpClient how to set the TIMEOUT on a request and response


I am guessing many people come here because of the title and because the HttpConnectionParams API is deprecated.

Using a recent version of Apache HTTP Client, you can set these timeouts using the request params:

HttpPost request = new HttpPost(url);RequestConfig requestConfig = RequestConfig.custom()  .setSocketTimeout(TIMEOUT_MILLIS)  .setConnectTimeout(TIMEOUT_MILLIS)  .setConnectionRequestTimeout(TIMEOUT_MILLIS)  .build();request.setConfig(requestConfig);

Alternatively, you can also set this when you create your HTTP Client, using the builder API for the HTTP client, but you'll also need to build a custom connection manager with a custom socket config.

The configuration example file is an excellent resource to find out about how to configure Apache HTTP Client.


The exceptions you'll see will be ConnectTimeoutException and SocketTimeoutException. The actual timeout values you use should be the maximum time your application is willing to wait. One important note about the read timeout is that it corresponds to the timeout on a socket read. So it's not the time allowed for the full response to arrive, but rather the time given to a single socket read. So if there are 4 socket reads, each taking 9 seconds, your total read time is 9 * 4 = 36 seconds.

If you want to specify a total time for the response to arrive (including connect and total read time), you can wrap the call in a thread and use a thread timeout for that. For example, I usually do something like this:

Future<T> future = null;future = pool.submit(new Callable<T>() {    public T call() {        return executeImpl(url);    }   }); try {    return future.get(10, TimeUnit.SECONDS);}   catch (InterruptedException e) {    log.warn("task interrupted", name);}   catch (ExecutionException e) {    log.error(name + " execution exception", e); }   catch (TimeoutException e) {    log.debug("future timed out", name);}

Some assumptions made in the code above are: 1) this is in a function with a url parameter, 2) it's in a class with a name variable, 3) log is a log4j instance, and 4) pool is a some thread pool executor. Note that even if you use a thread timeout, you should also specify a connect and socket timeout on the HttpClient, so that slow requests don't eat up the resources in the thread pool. Also note that I use a thread pool because typically I use this in a web service so the thread pool is shared across a bunch of tomcat threads. You're environment may be different, and you may prefer to simply spawn a new thread for each call.

Also, I've usually see the timeouts set via member functions of the params, like this:

params.setConnectionTimeout(10000);params.setSoTimeout(10000);

But perhaps your syntax works as well (not sure).