超时时间超过了我在“java.net.URLConnection”中设置的时间
我正在尝试为 java.net.URLConnection
设置一个超时,如下所示:
URL url = new URL("http://google.com");
URLConnection con = url.openConnection();
con.setConnectTimeout(2000);
con.setReadTimeout(2000);
InputStream in = con.getInputStream();
doc = new Tidy().parseDOM(in, null);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//td//span");
Node form = (Node) expr.evaluate(doc, XPathConstants.NODE);
问题是,当我将超时设置为 2000(2 秒)时,它等待的时间会超过它(例如 20 秒,因为我我自己统计的)直到抛出Timeout异常。
有什么问题吗?
如何将超时设置为完全按照我设置的值工作?
I'm trying to set a timeout for java.net.URLConnection
as this:
URL url = new URL("http://google.com");
URLConnection con = url.openConnection();
con.setConnectTimeout(2000);
con.setReadTimeout(2000);
InputStream in = con.getInputStream();
doc = new Tidy().parseDOM(in, null);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//td//span");
Node form = (Node) expr.evaluate(doc, XPathConstants.NODE);
The problem is that while I set timeout to 2000 (2 seconds) it waits more than it (for example 20 seconds as I counted by myself) until throwing Timeout exception.
What is the problem?
How Can I set the timeout to work exactly at the value I set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
readTimeOut
在 Sun (Oracle) 的实现中无法可靠地工作。这甚至在 JavaDocs:不过,您可以使用线程或计时器来模拟超时。将连接传递给子线程,并要求该线程在超时到期后调用
disconnect
或类似的操作。The
readTimeOut
is not working in Sun's (Oracle's) implementation reliably. This is even mentioned in the JavaDocs:You can simulate timeouts using threads or timers though. Pass the connection to a child thread, and ask that thread to call
disconnect
or something similar after the timeout expires.