问题描述
我使用 apache httpclient 4.4 来做 https 请求,我可以不断看到 org.apache.http.NoHttpResponseException
.
I'm using apache httpclient 4.4 to do https requests, and I can constantly to see org.apache.http.NoHttpResponseException
.
这是我创建 httpclient 的代码.
Here's my code to create the httpclient.
TrustManager[] trustAllCerts =
new TrustManager[] { new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} };
SSLContext sslcontext = null;
try {
sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
logger.warn(e.getMessage());
} catch (KeyManagementException e) {
logger.warn(e.getMessage());
}
// Allow TLSv1 protocol only
final SSLConnectionSocketFactory sslsf =
new SSLConnectionSocketFactory(sslcontext,
new String[] { "TLSv1" }, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create().register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm =
new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
在执行请求之前,我会执行cm.closeExpiredConnections();
和conMgr.closeIdleConnections(30, TimeUnit.SECONDS)
.我在阅读这个问题
Before execute the request, I do cm.closeExpiredConnections();
and conMgr.closeIdleConnections(30, TimeUnit.SECONDS)
. I added this after I read the answer of this question
还有什么我需要做的吗?
Anything more I need to do?
推荐答案
终于自己解决了.如果前一个响应给出标题,connections=close",下一个请求总是得到这个异常.所以,当看到这个标题时,多放两行
Finally figured it out on my own. If the previous response gives header, "connections=close", next request always gets this exception. So, when seeing this header, put 2 more lines
conManager.closeExpiredConnections();
conManager.closeIdleConnections(0, TimeUnit.SECONDS);
让连接管理器关闭连接,以便下次请求不会使用该连接.
to let connection manager close the connection so that the connection won't be used by the next request.
这篇关于如何解决org.apache.http.NoHttpResponseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!