我正在使用apache httpclient 4.4来执行https请求,我可以不断看到org.apache.http.NoHttpResponseException
。
这是我创建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)
。我在阅读this question
还有什么我需要做的吗?
答案 0 :(得分:4)
终于把它弄清楚了。如果先前的响应给出了标题,&#34; connections = close&#34;,则下一个请求始终会获得此异常。所以,当看到这个标题时,再添加2行
conManager.closeExpiredConnections();
conManager.closeIdleConnections(0, TimeUnit.SECONDS);
让连接管理器关闭连接,以便下次请求不会使用该连接。
答案 1 :(得分:3)
解决此问题的另一种方法是将org.apache.http.impl.client.AbstractHttpClient httpClient
配置为永不重用连接:
httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
可以在org.apache.http.impl.client.HttpClientBuilder builder
上配置相同的内容:
builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());