Java:HttpClient 4.1.2:ConnectionTimeout,SocketTimeout值设置无效

时间:2012-03-15 18:01:33

标签: java apache-httpclient-4.x

我使用的是HttpClient 4.1.2。将ConnectionTimeout和SocketTimeout设置为值永远不会有效。

代码:

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

如果服务器关闭,那么连接超时永远不会超过400毫秒,当它必须按照配置超时~30毫秒时。

套接字超时的情况也是如此,将睡眠放入doGet()5000毫秒将抛出一个套接字超时,它将永远不会在配置的60毫秒左右。它需要超过500毫秒。

有人可以建议如何配置HttpClient 4.1.2,使其在配置的时间内超时吗?

2 个答案:

答案 0 :(得分:13)

需要将HttpConnectionParams传递给连接管理器(请参阅this question)。使用DefaultHttpClient时,您可以设置以下参数:

    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

另见documentation

答案 1 :(得分:7)

你可以尝试这个(适用于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();