简体   繁体   中英

Apache HttpClient Persistent Connection usage

What is the right way for me to use the same TCP connection when using Apache HttpClient?

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.

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:

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

inside of the loop used a new TCP connection each time. Turns out that HttpClient will automatically try and reuse the connection for the same 'HttpClient' object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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