在网络异常的情况下,可能会发生连接超时,进而导致程序僵死而不再继续往下执行。在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);
}
}
}