【问题标题】:JSoup timeout not working as expectedJSoup 超时未按预期工作
【发布时间】:2015-12-17 04:32:27
【问题描述】:

我正在尝试使用 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?
  • 我正在使用 JSoup 1.8.3 版
  • 我能够重现您的发现。我建议您提交错误报告@@github.com/jhy/jsoup/issues
  • 已提交问题,谢谢

标签: java timeout jsoup socket-timeout-exception


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    它设置连接和读取超时。读取超时是指时间 读取之间。如果您有一台服务器长时间传送内容 时间,但每次读取

    实现最大计时器可能会很好,但事实并非如此 直截了当(需要一个监控线程和一个实用的方法来 关闭连接),这不是许多其他人所拥有的 要求。

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

    【讨论】:

      【解决方案3】:
      /**
       * 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);”也许修好了!

      【讨论】:

        猜你喜欢
        • 2017-04-23
        • 1970-01-01
        • 1970-01-01
        • 2016-06-22
        • 2022-01-23
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多