2012-03-15 8 views
5

Tôi đang sử dụng HttpClient 4.1.2. Đặt ConnectionTimeout và SocketTimeout thành một giá trị không bao giờ hiệu quả.Java: HttpClient 4.1.2: ConnectionTimeout, giá trị SocketTimeout được đặt không hiệu quả

mã:

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

Nếu server bị down, sau đó thời gian chờ kết nối là không bao giờ trước 400 ms khi nó có để thời gian chờ tại ~ 30 ms như cấu hình.

Tương tự trường hợp cho Thời gian chờ của ổ cắm, việc đặt một giấc ngủ vào doGet() trong 5000 mili giây sẽ làm mất thời gian chờ của ổ cắm sẽ không bao giờ ở khoảng 60 mili giây như được định cấu hình. Phải mất hơn 500 ms.

Có ai có thể gợi ý cách cấu hình HttpClient 4.1.2 sao cho nó có thời gian trong khoảng thời gian đã định cấu hình?

Trả lời

12

HttpConnectionParams cần được chuyển cho người quản lý kết nối (xem this question). Khi sử dụng DefaultHttpClient bạn có thể thiết lập các thông số như thế này:

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

Xem documentation cũng!

+1

Ném 'java.lang.UnsupportedOperationException' – Niklas

+3

' httpclient.getParams() 'bị phản đối từ 4.3 – oleh

5

Bạn có thể thử này (chỉ hoạt động với 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();