4

I am trying to get the web status for a given page. However when its a 404 error, the page does not return the status code, rather it throws and error.

int status= webClient.getPage("website").getWebResponse().getStatusCode();
System.out.println( status);

Any Ideas?

I am looking to see when sites time out, however for testing purposes I malformed the url of the desired website to see if I can even see a 404.

2 Answers 2

14

According to this

You can do this:

webclient.setThrowExceptionOnFailingStatusCode(False)

****EDIT ***

This does print out your status code:

 WebClient webClient = new WebClient();
 webClient.setThrowExceptionOnFailingStatusCode(false);
 int status = webClient.getPage("http://google.co.uk/ffffff").getWebResponse()
            .getStatusCode();
 System.out.println(status);

Prints out 404 - your status code.

Sign up to request clarification or add additional context in comments.

4 Comments

No, I want to get the status code of a webpage. Even if its a 404 error.
Updated my answer. it works unless I'm missing out on what your asking. 404 is the http status code
Your case given works, however the specific website I am trying to use does not work for some odd reason.
What do you mean it doesn't work? what exception does it throw?
0

Alternatively, you can continue to allow the FailingHttpStatusCodeException to be thrown (true). Then within the catch clause get the error status code.

...
int status = 0;
Object page = null;
try {
     page = webClient.getPage(webRequest);
     webClient.close();
     if (page instanceof UnexpectedPage) {
         status = ((UnexpectedPage) page).getWebResponse().getStatusCode();
     } else if (page instanceof HtmlPage) {
         status = ((HtmlPage) page).getWebResponse().getStatusCode();
     }
     // do something else ...
} catch (FailingHttpStatusCodeException | IOException e) {
     if (e instanceof FailingHttpStatusCodeException) {
          status = ((FailingHttpStatusCodeException) e).getStatusCode();
     }
     // do something else ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.