无法连接网站时的Jsoup错误处理 [英] Jsoup error handling when couldn't connect to website
本文介绍了无法连接网站时的Jsoup错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当程序无法连接到网站时,如何在Jsoup上进行错误处理?
How do I do error handling on Jsoup when the program fails to connect to the website?
例如,该网站不存在,我想向用户显示错误消息
For example that the website doesn't exist and I would like to print error message to the user
下面的代码显示了我连接到某个网站的方式,但是我想要的是,如果该网站不存在,我希望它打印错误消息.
The code below shows the way I connected to a certain website but what I want is that if the website doesn't exist, I wanted it to print error messages.
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();
}
推荐答案
尝试一下,
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();
}
这篇关于无法连接网站时的Jsoup错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文