【问题标题】:Jsoup error handling when couldn't connect to website无法连接到网站时的 Jsoup 错误处理
【发布时间】:2013-11-06 07:02:03
【问题描述】:

程序无法连接网站时,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();
}

【问题讨论】:

    标签: java html jsoup


    【解决方案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();
    }
    

    【讨论】:

    • 我可以将在线Document doc = connection.get(); 更改为例如Document doc = Jsoup.connect("https://asdasdasd.com").get(); 吗?因为我在connection.get() 上遇到错误。
    猜你喜欢
    • 2012-05-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多