-->

HttpUrlConnection how to set SO_KEEPALIVE

2019-12-16 19:43发布

问题:

Is there any way to set socket level options (like SO_KEEPALIVE) for a JDK stdlib HttpUrlConnection? I'm trying to figure out a way to GET HTTP requests that doesn't fall victim to occasional "hanging" connections (which seem to occur because of network packet loss every so often). A more robust HTTP client. I know there is the setReadTimeout method but I am trying to find something to nudge the TCP stream back into life, instead of just aborting it, as the read timeout seems to. Or at least report that the connection failure has occurred instead of hanging forever on a read. But that also allows the read to come back "whenever it wants to" assuming the connection is "still active."

With some examination it appears that the default for SO_KEEPALIVE is "off" for both the C layer and Java level sockets.

回答1:

This is founded on not one but three fallacies.

  1. SO_KEEPALIVE doesn't 'nudge the TCP stream back into life', despite its poorly chosen name. It just detects dead connections, after a default interval of two hours. It isn't what you're looking for.

  2. A read timeout doesn't abort the connection. It throws a SocketTimeoutException. The connection is still alive, and a subsequent read may succeed.

  3. Dropped packets are detected and retransmitted in TCP.

Use a read timeout.



标签: java http