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.