【问题标题】:httpclient unable to send more than two requestshttpclient 无法发送两个以上的请求
【发布时间】:2015-06-14 14:40:57
【问题描述】:

我正在编写一个客户端-服务器应用程序。我在客户端使用CloseableHttpClient 发送GET 请求。我想向服务器发送 5 个 GET 请求。但是,只有我收到前两个请求的响应。 这是我的客户代码:

 import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


public class Test {

    public static void main(String[] args) {
        HttpGet getreq = new HttpGet("http://shalakha:8089/Gateway/ReverseInvokeListener");
        CloseableHttpClient c1 = HttpClients.createMinimal();
        try {
            for(int i=0;i<5;i++){
            CloseableHttpResponse resp = c1.execute(getreq);
            System.out.println(resp);
        }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

这是我得到的回复:

HTTP/1.1 200 OK [Server: Apache-Coyote/1.1, Set-Cookie: JSESSIONID=0D4ABDC362FEC3030A5EE3709F3096FD; Path=/Gateway, CLIENTREQ: NO, Content-Length: 0, Date: Thu, 09 Apr 2015 09:22:22 GMT]
HTTP/1.1 200 OK [Server: Apache-Coyote/1.1, CLIENTREQ: NO, Content-Length: 0, Date: Thu, 09 Apr 2015 09:22:26 GMT]

其中“CLIENTREQ”​​是我在发送响应时从服务器端添加的自定义标头。

任何关于必须是什么原因的指针? server.xml 中的 connectionTimeout 设置为“-1”,表示无限超时。

【问题讨论】:

    标签: apache tomcat6 apache-httpclient-4.x


    【解决方案1】:

    您的代码泄露了所有可用的连接(默认为两个)并耗尽了连接池。您需要关闭响应对象以确保将连接释放回池。

    http://hc.apache.org/httpcomponents-client-4.4.x/tutorial/html/fundamentals.html#d5e145

    【讨论】:

    • 我没有关闭响应,因为稍后我将通过将响应传递给另一个线程来处理响应。如果我关闭响应对象,它的流将被关闭,以后我将无法读取响应对象。如何保留对象以便以后读取?
    • 您可以将 CloseableHttpResponse 传递给另一个线程,并让该线程在完成读取响应后关闭响应
    • @ok2c Golang 的 httpclient 和 worker 每秒可以处理大约 160 个请求,而带有 ExecutorService 的 Java 客户端(基于 HttpURLConnection)每秒不能超过 33 个请求是正常的吗...相同的客户端机器,相同的服务器 api?老实说,我只是想听听您的意见,因为我必须做出一些快速的决定。
    • "你的代码泄露了所有可用的连接(默认是两个)"你能帮我增加两个的默认限制吗?您从哪里获得有关默认限制的文档?
    • 链接现在是404ing。我也有这个问题,无法弄清楚为什么会失败,实现为 ClosableHTTPResponse 并关闭,现在没有问题......遗憾的是,在这种情况下,默认情况下它似乎没有给出任何错误......只是挂了..
    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多