2016-10-18 60 views
0
public HttpResponseBean get(String url, Map<String, String> headers) throws Exception { 
     logger.debug("Sending get request..."); 

     HttpClient httpClient = null; 
     try { 
      int timeout = 30 * 1000; // 30 seconds 
      RequestConfig requestConfig = RequestConfig.custom() 
        .setConnectTimeout(timeout) 
        .setConnectionRequestTimeout(timeout) 
        .setSocketTimeout(timeout).build(); 
      httpClient = HttpClients.custom() 
        .setDefaultRequestConfig(requestConfig).build(); 
      HttpGet httpGetRequest = new HttpGet(url); 

      if (headers != null) { 
       for (Entry<String, String> entry: headers.entrySet()) { 
        httpGetRequest.addHeader(new BasicHeader(entry.getKey(), entry.getValue())); 
       } 
      } 

      HttpResponse response = httpClient.execute(httpGetRequest); 
      HttpResponseBean hrb = new HttpResponseBean(response); 
      logger.debug("Get response: Response: " + hrb.toString()); 
      return hrb; 
     } finally { 
      closeConnection(httpClient); 
     } 
    } 

這在大多數情況下都能正常工作......但偶爾它會卡在握手之中,並會一直持續到服務器(tomcat)重新啓動。 按照此鏈接看起來像一個bug - >apache httpclient 4.3 not timing outHttpClient握手永久卡住

有沒有辦法呢?我正在使用httpclient 4.4.1

回答

0

有沒有辦法呢?我正在使用httpclient 4.4.1

這裏是associated bug on the Apache site。它看起來像人們有4.4.1版本的問題:

我有版本4.4.1這個問題。起初我忽略了這個線程,因爲它在4.3中被標記爲已解決。

但是,這似乎已經在4.5.1版本中得到解決。如果可能,我鼓勵你升級。

我在版本4.3.4上遇到過這個問題。我升級到4.5.1,問題在那裏得到修復。

這裏的附加信息:

在4.3.4版本中,HTTP://工作的罰款,並在1秒後超時。使用https時,請求會掛起超過1秒鐘,並掛起,直到服務器關閉TCP連接。

在4.5.1版本中,[正確] HTTP行爲是相同的,並採用https我有以下異常:[...] org.apache.http.conn.ConnectTimeoutException: Connect to localhost:6171 [localhost/127.0.0.1] failed: Read timed out

希望這有助於。