-1

In my Java servlet, I want to perform some actions depending on the status code returned from a request to a url.

My code looks like this:

String source = "http://urltoparse.org/name/date";
boolean validQuery = jsoupHandler.sourceExists(source);

int statusCode = jsoupHandler.srcExists(source);
response.getWriter().println("stat: " + statusCode);

jsoupHandler:

public class JSoupHandler {
    public int srcExists(String source) throws IOException {
        Connection.Response resp = Jsoup.connect(source).execute();
        System.out.println("status" + resp.statusCode());
        return resp.statusCode();
    }
}

When the statusCode == 200, it prints

stat: 200 in the browser and status200 in my console for jsouphandler.

However, when I put in a source that should return a 404, like this:

String source = "http://urltoparse.org/name/date2";

The browser prints nothing and my console prints an error like this:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, URL=http://urltoparse.org/name/date2

Why do the print statements for the browser and console both not print the status code? I want to do something like

if (statusCode != 200) {
//do something
}

but I'm unable to get into this conditional statement.

I've looked at this link: Jsoup error handling when couldn't connect to website

but couldn't get it to work for me.

Community
  • 1
  • 1
matcha
  • 81
  • 1
  • 9

1 Answers1

2

Add

.ignoreHttpErrors(true)

to your request.

See API: https://jsoup.org/apidocs/org/jsoup/Connection.html#ignoreHttpErrors-boolean-

Frederic Klein
  • 2,846
  • 3
  • 21
  • 37
  • I'm using Connection.Response, not Connection.Request, according to this: 'https://jsoup.org/apidocs/org/jsoup/Connection.Response.html#statusCode--' .statusCode() should return whatever the status code is, I'm not sure how I would get that if I used Connection.Request – matcha Sep 19 '16 at 16:08
  • `Jsoup.connect(source).execute();` is a request and you are storing the response. The request leads to the http error and by setting `Jsoup.connect(source).ignoreHttpErrors(true).execute();` you are telling Jsoup to ignore the http errors when connecting, otherwise Jsoup throws exceptions on http errors. – Frederic Klein Sep 19 '16 at 16:38