[英]Error in connect to website jsoup project(The method connect(String) is undefined for the type Jsoup)
[英]Jsoup error handling when couldn't connect to website
當程序無法連接到網站時,如何在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();
}
試試這個
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.