简体   繁体   English

Apache HttpClient持久连接用法

[英]Apache HttpClient Persistent Connection usage

What is the right way for me to use the same TCP connection when using Apache HttpClient? 使用Apache HttpClient时,使用相同的TCP连接的正确方法是什么?

My code currently is: 我的代码当前是:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();
for (int i = 0; i < 100; i++)
{
    CloseableHttpResponse response = httpClient.execute(new HttpGet("http://www.google.co.uk"), httpContext);
    String responseBody = EntityUtils.toString(response.getEntity());
    EntityUtils.consume(response.getEntity());
    response.close();
}

I have tried using the code with and without response.close() but the times vary each run that I can't figure out which one is keeping the connection open. 我试过使用带有和不带有response.close()的代码,但是每次运行的时间各不相同,因此我无法弄清楚哪个保持了打开状态。

Can somebody please explain to me how I can keep the connection open? 有人可以告诉我如何保持连接打开吗?

So after messing around with TCPView I figured out that placing the lines: 因此,在弄乱TCPView之后,我发现放置这些行:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();

inside of the loop used a new TCP connection each time. 循环内部每次都使用新的TCP连接。 Turns out that HttpClient will automatically try and reuse the connection for the same 'HttpClient' object. 事实证明HttpClient会自动尝试为同一“ HttpClient”对象重用该连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM