简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM