超时时间超过了我在“java.net.URLConnection”中设置的时间

发布于 2024-12-25 17:40:15 字数 583 浏览 4 评论 0原文

我正在尝试为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有你我更好 2025-01-01 17:40:15

readTimeOut 在 Sun (Oracle) 的实现中无法可靠地工作。这甚至在 JavaDocs

此方法的某些非标准实现会忽略指定的
暂停。要查看读取超时设置,请调用 getReadTimeout()。

不过,您可以使用线程或计时器来模拟超时。将连接传递给子线程,并要求该线程在超时到期后调用 disconnect 或类似的操作。

The readTimeOut is not working in Sun's (Oracle's) implementation reliably. This is even mentioned in the JavaDocs:

Some non-standard implementation of this method ignores the specified
timeout. To see the read timeout set, please call getReadTimeout().

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文