Apache HttpClient 4.3无法超时

7

我在使用以下代码时遇到了Apache HttpClient (4.3) post请求超时的问题:

RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(4000).setConnectTimeout(4000)
        .setSocketTimeout(4000).build();

CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext)
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
        .setDefaultRequestConfig(requestConfig).build();

HttpPost post = new HttpPost("https://localhost:" + connection.getLocalPort() + "/API/webservice.asmx");

StringEntity stringE = new StringEntity(REQUEST);
    post.setEntity(stringE);

CloseableHttpResponse response = client.execute(post);

我通过专有的API获取连接和端口。当一切顺利时,代码可以正常工作,但由于连接不良等原因,有时候代码会永久地挂在 client.execute(post) 上。我在实现超时方面是否存在问题?或者是否有其他方法可以使调用超时,以便我不会无限期地困在其中。

1个回答

5

HttpClient 4.3版本中存在一个与https连接相关的bug。在尝试进行SSL握手之前,套接字超时未设置在套接字上。在握手期间,线程可能会挂起等待套接字读取。而HttpClient 4.2则没有这个bug。


2
参考(看起来在4.3.4中已经修复):https://issues.apache.org/jira/browse/HTTPCLIENT-1478 - Greg
2
请注意,当通过SSL/HTTPS连接时,实际上似乎已在4.3.4/4.3.5中修复。 - centic
3
如果您仔细阅读HTTPCLIENT-1478,您会发现有几个人抱怨它实际上没有被修复。我正在使用4.4.1版本,可以确认这个问题仍然存在。 - GaspardP
@GaspardPetit 你说得对。我正在使用HttpClient 4.3.5通过HTTPS进行通信。我已将连接超时设置为1分钟,但即使15分钟后连接仍未关闭。 - sunil
1
刚刚使用HttpClient 4.5.2进行了测试,现在问题已经被彻底解决了。请确保设置套接字配置: PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(35000).build()); - Theo
这是刚刚对我有效的方法。使用了HttpClient 4.5.13,并像Theo建议的那样将默认的Socket超时设置为PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(35000).build()); - Abhishek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接