Apache HttpComponents HttpClient timeout - java

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.

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();

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);

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);

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.

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)

Related

Httpclient 4.5 taking double time for closing the http connection

I have given the connectiontimeout 5000 milliseconds(5 second) but actually it takes 10127 milliseconds(10.127 second)
if connectiontimeout=10000 milliseconds(10 second) then it is taking 20032 milliseconds(20 second) for connection time out
below is the code which i tried.
public static void getTest()
{
long start=0;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://testing url");
RequestConfig config=null;
config = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000)
.build();
httpGet.setConfig(config);
start = System.currentTimeMillis();
httpClient.execute(httpGet);
} catch (Exception e) {
long end=System.currentTimeMillis();
System.out.println("total time in Milliseconds:="+(end-start));
}
}
The reason is unsuccessful HTTP POST request will be automatically re-sent to the server. Unsuccessful post means, in this case, the server did not send a valid HTTP response or an IOException occurred and HTTP PostRetry default value is true in JVM. There are servral ways to prevent from silent HttpRetry please refer below-mentioned table.
That's the main reason for doubled the exact timeout.

How to add OkHttp's deprecated code in eclipse?

I am new with Android. Please guide me. Here is my code. How can i add or change the code with OkHttp?
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient =HttpClientBuilder.create().build();
try{
HttpPost httppost = new HttpPost("http://10.0.2.2/hari/test.php");
StringEntity se = new StringEntity("envelope",HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
I had problems when I am using the deprecated code. How can i use the OkHttp in my code? I do try include OkHttp in my code but there are more errors detected. I am using android API 20 and above. I also got warning for utf_8.
What should i do?

HttpClient and Connection Timeout

I send http requests over Apache HttpClient and my code is here:
HttpHost proxy = new HttpHost("78.1.1.222", 80);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Authorization","Basic " + encoding);
httpGet.addHeader("Cache-Control", "no-cache");
httpResponse = httpClient.execute(httpGet);
responseCode=httpResponse.getStatusLine().getStatusCode();
........
........(code continue..)
My question is that how can I add connection timeout time to this code?
Note that I must use proxy with that and I use HttpClient 4.4 .
http://www.baeldung.com/httpclient-timeout explains various ways to set the connection timeout.

Why does an HttpGet works without timeouts but with timeouts causes an internal server error?

I don't know how the HttpClient works exactly but I find it quite strange that I get an internal server error if I initialise the httpclient with new DefaultHttpClient(httpParameters) but everythings works fine if I initialise it with new DefaultHttpClient(). I should additionally mention that the error does not occur on the first request. Here's a piece of my code, are there any errors?
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpclient.execute(new HttpGet(url));
int statusCode = response.getStatusLine().getStatusCode();
Try to change
HttpClient httpclient
to
DefaultHttpClient httpclient

HttpClient - setting a "global" socket timeout, and a separate timeout per request

With HttpClient, I am setting the default socket/connection timeout with the following:
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 30000);
HttpConnectionParams.setConnectionTimeout(params, 30000);
mClient = new DefaultHttpClient(connectionManager, params);
I'm wondering if I can override these values on a per request basis?
Edit: Would this work?
HttpParams params = req.getParams(); // req is an HttpRequest object
HttpConnectionParams.setSoTimeout(params, 60000);
HttpConnectionParams.setConnectionTimeout(params, 60000);
I tried it, and it seems to, but it's hard to test/create a situation where a timeout will occur.
If you are using HttpClient 4.0 you could do this :
mClient = new DefaultHttpClient(connectionManager, params) {
protected HttpParams determineParams(HttpRequest req) {
//Fill in your impl here
}
You can simply set those parameters on the request object. For details see:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e391

Categories