当程序无法连接到网站时,如何在Jsoup上进行错误处理?
例如网站不存在,我想向用户打印错误消息
下面的代码显示了我连接到某个网站的方式,但我想要的是,如果该网站不存在,我希望它能够打印错误消息。
Document doc;
try {
// need http protocol
doc = Jsoup.connect("https://forum.lowyat.net/user/OldSchoolJoke").get();
// get page title
String title = doc.title();
//System.out.println("title : " + title);
// get all links
Elements links = doc.select("div.postdetails");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("div"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
试试这个,
try{
Connection.Response response = Jsoup.connect("https://asdasdasd.com")
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(10000)
.ignoreHttpErrors(true).
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
Document doc = Jsoup.connect("https://asdasdasd.com").get();
Elements links = doc.select("div.postdetails");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("div"));
System.out.println("text : " + link.text());
}
}
else {
System.out.println("received error code : " + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
}