简体   繁体   中英

Apache HttpClient TCP Keep-Alive (socket keep-alive)

I have http request that takes too much time to be processed by the server (about 5 minutes). Because connection becomes idle for 5 minutes, proxy server shutdowns the connection. I'm trying to use TCP Keep-Alive in Apache DefaultHttpClient to make connection be alive for a long time (Not confuse TCP Keep-Alive with HTTP Keep-Alive that simply doesn't closes connection after response is sent).

Apache http core has following parameter SO_KEEPALIVE: http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/params/CoreConnectionPNames.html#SO_KEEPALIVE . However, due to DefaultHttpClient javadocs I can't customize client's behavior with that parameter: https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/DefaultHttpClient.html .

I did this, however, seems it doesn't work:

HttpClient client = getHttpClient();
client.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, true);

Do you know how to make DefaultHttpClient use TCP Keep-Alive strategy?

To make it work I needed to set keepalive timeouts. But they can be set only on OS level, not in Java code. As I know, it's not possible to set keepalive timeouts in Java code.

Here is how I set them on Linux:

sudo sysctl -w net.ipv4.tcp_keepalive_time=60
sudo sysctl -w net.ipv4.tcp_keepalive_intvl=60
sudo sysctl -w net.ipv4.tcp_keepalive_probes=10

Value is amount of seconds.

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