Jsoup error handling when couldn't connect to website

前端 未结 1 639
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 10:33

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

相关标签:
1条回答
  • 2021-01-21 11:17

    Try this one,

    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 讨论(0)
提交回复
热议问题