3

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 to the user

The code below shows the way I connected to a certain website but what I want is that if the website doesn't exist, I wanted it to print error messages.

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();
}
Poh Sun
  • 75
  • 1
  • 2
  • 11

1 Answers1

2

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();
}
yilmazburk
  • 907
  • 9
  • 17
  • Can I change on the line `Document doc = connection.get();` to for example `Document doc = Jsoup.connect("https://asdasdasd.com").get();`? Because I'm getting error on the `connection.get()`. – Poh Sun Oct 27 '13 at 14:35