java - Apache HttpComponents BasicHttpClientConnectionManager

标签 java apache-httpclient-4.x apache-httpcomponents

我最近从 java.net 切换过来至org.apache.http.client ,我设置了一个 ClosableHttpClientHttpClientBuilder 。作为连接管理器,我使用 BasicHttpClientConnectionManager .

现在我遇到一个问题,当我创建一些 HTTP 请求时,我经常遇到超时异常。连接管理器似乎保持连接打开以重用它们,但如果系统空闲几分钟,那么此连接将超时,当我发出下一个请求时,我得到的第一件事就是超时。再次重复相同的请求通常不会出现任何问题。

有没有办法配置 BasicHttpClientConnectionManager为了不重用其连接并每次创建一个新连接?

最佳答案

有几种方法可以解决这个问题

  1. 删除不再需要的空闲连接。下面的代码通过在每次 HTTP 交换后关闭持久连接来有效地禁用连接持久性。

    BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    ...
    try (CloseableHttpResponse response = httpclient.execute(new HttpGet("/"))) {
        System.out.println(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    cm.closeIdleConnections(0, TimeUnit.MILLISECONDS);
    
  2. 将连接保持 Activity 时间限制为相对较小的时间

    BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(cm)
            .setKeepAliveStrategy((response, context) -> 1000)
            .build();
    try (CloseableHttpResponse response = httpclient.execute(new HttpGet("/"))) {
        System.out.println(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    
  3. (推荐) 使用池连接管理器并将连接总生存时间设置为有限值。与池连接管理器相比,使用基本连接管理器没有任何好处,除非您的代码预计在 EJB 容器中运行。

    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionTimeToLive(5, TimeUnit.SECONDS)
            .build();
    try (CloseableHttpResponse response = httpclient.execute(new HttpGet("/"))) {
        System.out.println(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    

关于java - Apache HttpComponents BasicHttpClientConnectionManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39139902/

相关文章:

java - 仅当 OkHttp 中表单字段不为 null 时才添加表单字段

java - Android 兼容屏幕和密度

java - 如何配置 apache httpcore 4 以使用代理?

java - 为什么 HttpClient 不发送指定的 Accept-Language 字段?

java - 我的简单 Java 程序不断出现 "Cannot find symbol",但不知道为什么

java - 从 PHP 到 Java。有什么建议吗?

java - 如何创建一个不验证 SSL 证书的 CloseableHttpPipelinedClient?

java - Apache HttpClient 响应内容长度返回 -1

java - URLEncodedUtils.parse() 是否保留顺序?

javax.net.ssl.SSLPeerUnverifiedException : Host name does not match the certificate subject provided by the peer