Java:HttpClient 4.1.2:ConnectionTimeout、SocketTimeout值集无效

Java:HttpClient 4.1.2:ConnectionTimeout、SocketTimeout值集无效,java,apache-httpclient-4.x,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

我正在使用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,使其在配置的时间内超时吗?

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

    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
也看到了

您可以尝试以下方法(适用于apache http客户端4.5.2):


Throws
java.lang.UnsupportedOperationException
httpclient.getParams()
自4.3版以来已被弃用
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();