如何解决org.apache.http.NoHttpResponseException

How to solve org.apache.http.NoHttpResponseException

我用的是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

的答案后添加了这个

我还需要做什么吗?

我终于自己弄明白了。如果上一个响应给出 header、"connections=close",下一个请求总是得到这个异常。所以,看到这个header,再放2行

conManager.closeExpiredConnections();
conManager.closeIdleConnections(0, TimeUnit.SECONDS);

让连接管理器关闭连接,以便下一个请求不会使用该连接。

解决此问题的另一种方法是将您的 org.apache.http.impl.client.AbstractHttpClient httpClient 配置为永不重用连接:

httpClient.setReuseStrategy(new NoConnectionReuseStrategy());

同样可以在org.apache.http.impl.client.HttpClientBuilder builder上配置:

builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());