java HttpURLConnection 超时默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45199702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:35:29  来源:igfitidea点击:

HttpURLConnection timeout defaults

javahttpurlconnection

提问by rogerdpack

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?

我似乎有时会遇到一些 tcp 请求“卡住”的问题,就像它在等待某些响应但连接已“切断”,因此永远不会有响应。这是具有默认超时的 HttpURLConnection 的预期行为吗?是否设置了合理的默认值,以便默认情况下我无法进入这种奇怪的“挂起”情况?

回答by rogerdpack

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

出现HttpURLConnection的“默认”超时为零,这意味着“没有超时”。

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 HttpURLConnectionand don't explicitly set (at least read) timeouts, your connection can get into a permanent stale state. By default. So always set setReadTimeoutto "something" or you might orphan connections (and possibly threads depending on how your app runs).

不幸的是,根据我的经验,使用这些默认值似乎会导致不稳定状态,具体取决于您与服务器的连接发生的情况。如果您使用 anHttpURLConnection并且没有明确设置(至少是读取)超时,则您的连接可能会进入永久陈旧状态。默认情况下。所以总是设置setReadTimeout为“something”,否则你可能会孤立连接(可能还有线程,这取决于你的应用程序的运行方式)。

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

从反复试验看来,setConnectTimeout不需要调用,因为套接字本身似乎内置了 2 分钟的“连接超时”(至少在 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 without these result in threads hanging "forever" without it.

修复/预测:始终设置 readTimeout (即使非常大),或使用不同的客户端,让您设置SO_KEEPALIVE。没有这些的默认值会导致线程在没有它的情况下“永远”挂起。