2

当程序无法连接到网站时,如何在 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();
}
4

1 回答 1

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();
}
于 2013-10-27T14:23:04.307 回答