Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : HttpClient 4.1.2 : ConnectionTimeout, SocketTimeout values set are not effective

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?

like image 655
Shadab Khan Avatar asked Mar 15 '12 18:03

Shadab Khan


2 Answers

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!

like image 104
Vlad Avatar answered Sep 22 '22 10:09

Vlad


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();
like image 22
Evgenii Bogdanov Avatar answered Sep 22 '22 10:09

Evgenii Bogdanov