HttpClient握手永远陷入困境

时间:2016-10-18 03:39:22

标签: java multithreading httpclient

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)重新启动。 根据此链接看起来像一个错误 - &gt; apache httpclient 4.3 not timing out

有没有办法解决这个问题?我使用的是httpclient 4.4.1

1 个答案:

答案 0 :(得分: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

希望这有帮助。