Niklas
Niklas

Reputation: 25453

Java HTTP Client request set timeout

I want to set the timeout of a request. This is the code, I've got so far.

final HttpClient httpclient = HttpClients.createDefault();
final HttpPost httppost = new HttpPost(address);
httppost.setHeader("Accept", "text/xml");
httppost.setHeader("Content-type", "application/xml; charset=UTF-8");
httppost.setEntity(new StringEntity(body));
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();

I've tried (does not work, keeps loading and ignores timeout)

// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
client = new DefaultHttpClient(httpParams);

and (this one throws java.lang.UnsupportedOperationException)

httpclient = HttpClients.createDefault();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);

Is there any other way for setting the timout? I don't really need the response so something like an asynchronous request could do the work too.

Upvotes: 3

Views: 8455

Answers (1)

Shishir Kumar
Shishir Kumar

Reputation: 8199

Apache's HttpClient has two separate timeouts: a timeout for how long to wait to establish a TCP connection, and a separate timeout for how long to wait for a subsequent byte of data.

HttpConnectionParams.setConnectionTimeout() is used for establishing a TCP connection, whereas HttpConnectionParams.setSoTimeout() is used while waiting for a subsequent byte of data.

// Creating default HttpClient
HttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParams = httpClient.getParams();

// Setting timeouts
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);

// Rest of your code
final HttpPost httppost = new HttpPost(address);
httppost.setHeader("Accept", "text/xml");
httppost.setHeader("Content-type", "application/xml; charset=UTF-8");
httppost.setEntity(new StringEntity(body));
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();

Upvotes: 4

Related Questions