当DNS无法访问时,URLConnection.setConnectTimeout()不起作用 [英] URLConnection.setConnectTimeout() does not work when DNS is unreachable
问题描述
以下是我的代码:
URL u = new URL("http://www.google.com");
URLConnection conn = u.openConnection();
conn.setConnectTimeout(3000);
conn.connect();
我的网络连接有时不稳定(我连接到无线路由器,但实际上我的路由器没有'有互联网接入)。当发生这种情况时,此代码将单独阻塞并最终抛出 UnknownHostException
。为什么 setConnectTimeout(3000)
在这种情况下不起作用?如何解决这个问题?
谢谢!
My network connection is sometimes unstable(I've connected to the wireless router but actually my router doesn't have Internet access). When that happens, this code will block for a lone time and finally throws UnknownHostException
. Why setConnectTimeout(3000)
doesn't work in this case? How to fix this?
Thanks!
------------更新---------------
------------update---------------
我的猜测是 conn.connect()
将首先查询DNS,但此操作没有时间限制。我已经尝试了 Socket
类,问题仍然存在。 setTimeout()
似乎不适用于DNS查询。
My guess is that conn.connect()
will query DNS first but there's no time limit for this operation. I've tried Socket
class and problem remains. setTimeout()
seems do not work for DNS query.
推荐答案
我发现了一个可以解决它的帖子。使用另一个线程来查询DNS以模拟超时:
http://thushw.blogspot.sg/2009/11/resolving-domain-names-quickly-with.html
I found a post that can work around it. Use another thread to query DNS to simulate timeout: http://thushw.blogspot.sg/2009/11/resolving-domain-names-quickly-with.html
这篇关于当DNS无法访问时,URLConnection.setConnectTimeout()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!