Monday, June 6, 2011

Configure Timeout for Apache HttpClient 4.0

Adding HTTP request timeout support to HttpClient 4.0  of Appache is quite an easy task. But not as straight forward as one might think. I needed to add such timeout for one of my HTTP requests. I expected to have a method named: "setTimout" or "setConnectionTimeout". But couldn't find any method regarding timeout. After a little digging I found how it can be done. Hope it will save you some time.
In general, all you have to do is create an instance of HttpParams and use it in order to define the connection timeout.
Let's see how the code looks:
package com.bashan.blog.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
/**
 * @author Bashan
 */
public class HttpRequest {
  public static void main(String[] args) throws Exception {
    // Set connection timeout
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5000);
    HttpConnectionParams.setSoTimeout(params, 5000);
    HttpClient httpClient = new DefaultHttpClient(params);
    HttpResponse response = httpClient.execute(new HttpGet("http://google.com"));
    System.out.print(EntityUtils.toString(response.getEntity()));
  }
}

You can see in the 3 lines marked in yellow, how the HttpParams class is used in order to define the connection timeout. Later an HttpClient instance is created with params that is passed to it.


You can download this class here.

5 comments:

  1. does not work....easy break....run in windows 7..............timeout is totally ignored........

    ReplyDelete
  2. Are you sure? This is kinda' strange. I don't think a timeout on Java is related with Windows 7...

    ReplyDelete