4

我正在尝试使用 JSoup 下载页面内容。如果整个操作(打开连接 + 读取)花费超过 8 秒,我想立即中止。我假设该timeout(int millis)方法的目的正是这样做的。根据javadoc:

设置请求超时(连接和读取)。如果发生超时,将抛出 IOException。默认超时为 3 秒(3000 毫秒)。超时为零被视为无限超时。

我编写了一个简单的代码来模拟该操作:

    final int TIME_OUT = 8000;
    final String USER_AGENT_STRING = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
    final String url = "http://reguler-pmb-tanggamus.va.web.id/";

    long time = System.currentTimeMillis();
    try {
        Document doc = Jsoup.connect(url).userAgent(USER_AGENT_STRING).timeout(TIME_OUT).get();
        System.out.println("Done crawling " + url + ", took " + (System.currentTimeMillis() - time) + " millis");
        System.out.println("Content: " + doc);
    } catch (Exception e) {
        System.out.println("Failed after " + (System.currentTimeMillis() - time) + " millis");
        e.printStackTrace();
    }

我试图在单线程环境中的几个“有问题的”网站上运行这个小脚本。我假设无论是成功还是捕获到异常,操作时间都不应超过 8 秒(8000 毫秒)。不幸的是,情况并非如此,因为有时它会在超过一分钟后成功(无一例外):

Done crawling http://reguler-pmb-tanggamus.va.web.id/, took 68215 millis
Content: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ...

有时(尽管很少)在一分钟多后失败(SocketTimeoutException)。

有没有人遇到过这种问题?

4

3 回答 3

1

OP 面临的问题似乎是 Jsoup 1.8.3 中的一个错误。

我能够重现您的发现。我建议您提交错误报告@github.com/jhy/jsoup/issues ( luksch )

OP 提供了一个问题:https ://github.com/jhy/jsoup/issues/628

于 2016-03-03T09:07:44.380 回答
0

JSoup 团队 (jhy) 回复了我的问题:

它设置连接和读取超时。读取超时是指读取之间的时间。如果您有一个服务器在很长一段时间内输出内容,但每次读取时间小于 8 秒,则它不会超时。

实现一个最大计时器可能会很好,但这并不简单(需要一个监视线程和一种关闭连接的实用方法),这不是许多其他人所要求的。

看来这个问题不会很快得到解决。

于 2016-04-04T08:15:39.023 回答
-1
/**
 * Set the maximum bytes to read from the (uncompressed) connection into the body, before the connection is closed,
 * and the input truncated. The default maximum is 1MB. A max size of zero is treated as an infinite amount (bounded
 * only by your patience and the memory available on your machine).
 * @param bytes number of bytes to read from the input before truncating
 * @return this Connection, for chaining
 */
Connection maxBodySize(int bytes);

Jsoup默认recv最大值为1MB

设置“Jsoup.connect(url).maxBodySize(0);” 也许修好了!

于 2016-09-08T06:38:35.037 回答