HttpURLConnection timeout defaults

青春壹個敷衍的年華 提交于 2019-12-18 04:05:13

问题


I seem to be having trouble with some tcp requests getting "stuck" at times, like it is waiting for some response but the connection has been "severed" so a response will never come. Is this expected behavior for HttpURLConnection with default timeouts? Are there sensible defaults set so that I can't get into this odd "hung" situation by default?


回答1:


Appears the "default" timeouts for HttpURLConnection are zero which means "no timeout."

Unfortunately, in my experience, it appears using these defaults can lead to an unstable state, depending on what happens with your connection to the server. If you use an HttpURLConnection and don't explicitly set (at least read) timeouts, your connection can get into a permanent stale state. By default. So always set setReadTimeout to "something" or you might orphan connections (and possibly threads depending on how your app runs).

It appears from trial and error that calling setConnectTimeout isn't required because the socket itself seems to have like a 2 minute "connect timeout" built in (at least in OS X).

You may also be able to set a "global default" for the timeouts by adjusting system properties.

Fix/prognosis: always set a readTimeout (even if very large), or use a different client that lets you set SO_KEEPALIVE. The default can result in your program hanging "forever" without it.



来源:https://stackoverflow.com/questions/45199702/httpurlconnection-timeout-defaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!