Default HttpURLConnection defaults

I seem to be having problems with some tcp requests that sometimes get stuck, for example waiting for a response, but the connection was “broken”, so the response never comes. Is this the expected behavior for HttpURLConnection with default timeouts? Are there any sensible defaults to prevent me from getting into this weird default freeze situation?

+9


source to share


2 answers


It appears that the "default timeouts" for HttpURLConnection are zero, which means "no timeout".

Unfortunately, in my experience, using these defaults can lead to an unstable state depending on what happens to your server connection. If you use HttpURLConnection

and do not explicitly set (at least read) timeouts, your connection can go into a persistent stale state. Default. So always set setReadTimeout

to "something", otherwise you might lose connectivity (and possibly threads depending on how your application is running).

It follows from trial and error that no call setConnectTimeout

is required because the socket itself seems to have a built in 2 minute connection timeout (at least on OS X).



You can also set a "global default" for timeouts by configuring system properties .

Fix / Prediction: Always set readTimeout (even if very large) or use another client that allows SO_KEEPALIVE to be set . The default can cause your program to freeze "forever" without it.

+18


source


I had a hard timeout error HttpURLConnection

on Android 4.3 - 9 platforms.

I have implemented setConnectTimeout(5000)

.

I have not implemented setReadTimeout(5000)

.

For Android 5.0 - 9.0 devices, the attempt connect()

always either establishes a connection or throws an exception.



However, on my Android 4.4 device, the attempt connect()

sometimes resulted in an infinite lock state.

The lock state of Android 4.4 depended on how the connection was lost:

  • weak WiFi (no blocking)
  • WiFi transfer to mobile (no blocking)
  • loss of internet connection with local WiFi router (blocked)

Example: Disconnecting the Ethernet cable between my modem and router always caused an infinite blocking state.

0


source







All Articles