3.1.5 Jsoup超时设置

在网络异常的情况下,可能会发生连接超时,进而导致程序僵死而不再继续往下执行。在Jsoup请求URL时,如果发生连接超时的情况,则会抛出下图所示的异常信息。
在这里插入图片描述
针对连接超时问题,Jsoup在请求URL时,可以由用户自行设置毫秒级别的超时时间,如程序3-8和3-9所示。如果不使用timeout方法设置超时时间,则默认超时时间为30毫秒。

//程序3-8
public class JsoupConnectUrl {
    public static void main(String[] args) throws IOException {
        //通过Jsoup创建和url的连接
        Connection connection = Jsoup.connect("https://searchcustomerexperience.techtarget.com/info/news");
        //获取网页的Document对象
        Document document = connection.timeout(10*1000).get();
        //输出HTML
        System.out.println(document.html());
    }
}
//程序3-9
public class JsoupConnectUrl {
    public static void main(String[] args) throws IOException {
        //获取响应
        Connection.Response response = Jsoup.connect("https://searchcustomerexperience.techtarget.com/info/news").method(Connection.Method.GET).timeout(10*1000).execute();
        //获取响应状态码
        int statusCode = response.statusCode();
        //判断响应状态码是否为200
        if (statusCode == 200) {
            //通过这种方式可以获得响应的HTML文件
            String html = new String(response.bodyAsBytes(),"gbk");
            //获取html内容,但对应的是Document类型
            Document document = response.parse();
            //这里html和document数据是一样的,但document是经过格式化的
            System.out.println(document);
            System.out.println(html);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值