I am using HttpClient 4.1.2. Setting ConnectionTimeout and SocketTimeout to a value is never effective.
code :
Long startTime = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 30);
HttpConnectionParams.setSoTimeout(params, 60);
HttpGet httpget = new HttpGet("http://localhost:8080/Test/ScteServer");
try {
startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(httpget);
}
catch(SocketTimeoutException se) {
Long endTime = System.currentTimeMillis();
System.out.println("SocketTimeoutException :: time elapsed :: " + (endTime-startTime));
se.printStackTrace();
}
catch(ConnectTimeoutException cte) {
Long endTime = System.currentTimeMillis();
System.out.println("ConnectTimeoutException :: time elapsed :: " + (endTime-startTime));
cte.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
Long endTime = System.currentTimeMillis();
System.out.println("IOException :: time elapsed :: " + (endTime-startTime) );
e.printStackTrace();
}
If the server is down, then the connection timeout is never before 400 ms when it has to timeout at ~ 30 ms as configured.
Same is the case for Socket Timeout, putting a sleep in doGet() for 5000 ms will throw a socket timeout which will never be at around 60 ms as configured. It takes more than 500 ms.
Can anyone suggest how to configure HttpClient 4.1.2 so that it times out around the configured time?
The HttpConnectionParams
need to be passed to a connection manager (see this question). When using the DefaultHttpClient
you can set these parameters like this:
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
See the documentation also!
You can try this (works with apache http-client 4.5.2):
int DEFAULT_TIMEOUT = 5000;
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_TIMEOUT)
.setConnectionRequestTimeout(DEFAULT_TIMEOUT)
.setSocketTimeout(DEFAULT_TIMEOUT)
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
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