Apache HttpComponents HttpClient timeout
Solution 1:
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();
Solution 2:
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);
Solution 3:
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);
Solution 4:
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.