2013-10-27 87 views
2

當程序無法連接到網站時,如何在Jsoup上執行錯誤處理?當無法連接到網站時出現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(); 
} 

回答

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(); 
} 
+0

我可以改變就行了'文獻DOC = connection.get();'到例如'文獻DOC = Jsoup.connect(「https://開頭。asdasdasd.com「)獲得();'?因爲我在'connection.get()'錯誤。 –

+0

看看編輯好的解決方案。也許它很有用。 – yilmazburk

相關問題