前期开发某一个需要访问其他网站的功能时考虑到是内网,未关注请求响应时间问题,在使用Jsoup时直接使用了默认的超时时间,今天发现一直出现问题,于是查了一下默认超时时间、超时时间配置等。
问题现象
在网络异常的情况下,可能会发生连接超时,进而导致程序僵死而不再继续往下执行。在Jsoup请求URL时,如果发生连接超时的情况,则会抛出下图所示的异常信息。
解决方式
针对连接超时问题,Jsoup在请求URL时,可以由用户自行设置毫秒级别的超时时间,如果不使用timeout方法设置超时时间,则默认超时时间为30毫秒。
示例代码一
public class JsoupConnectUrl {
public static void main(String[] args) throws IOException {
//通过Jsoup创建和url的连接
Connection connection = Jsoup.connect("https://swww.sammery.com");
//获取网页的Document对象
Document document = connection.timeout(10*1000).get();
//输出HTML
System.out.println(document.html());
}
}
示例代码二
public class JsoupConnectUrl {
public static void main(String[] args) throws IOException {
//获取响应
Connection.Response response = Jsoup.connect("https://www.sammery.com").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);
}
}
}
评论区