HttpURLConnection超时默认值 [英] HttpURLConnection timeout defaults

查看:463
本文介绍了HttpURLConnection超时默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

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

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).

从试验和错误看来,不需要调用 setConnectTimeout ,因为套接字本身似乎内置了2分钟的连接超时(至少在OS X)。

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).

您也可以通过调整系统属性

修复/ prognosis:始终设置readTimeout(即使非常大),或使用允许您设置 SO_KEEPALIVE 的其他客户端。默认情况下,如果没有它,程序会永远挂起。

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.

这篇关于HttpURLConnection超时默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆