JSoup超时设置不起作用

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)。
有人遇到过这种问题吗?

你在使用哪个版本的JSoup? - luksch
我正在使用JSoup版本1.8.3。 - KidCrippler
3
我能够重现你的发现。我建议你在https://github.com/jhy/jsoup/issues上提交错误报告。 - luksch
已提交问题,谢谢。 - KidCrippler
3个回答

1

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

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

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


0

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

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

实现最大计时器可能很好,但这并不简单(需要一个监视线程和一种实用的方法来关闭连接),而且没有多少人提出这样的要求。

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


-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默认接收的最大数据量为1MB

设置"Jsoup.connect(url).maxBodySize(0);"可能会解决这个问题!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接