Search code examples
javahtmlunit

HtmlUnit disable status code error exception


In HtmlUnit, how to disable throw exception when the requested page returns fail status code (like 4xx)? I need to get the status code, so if it throws an exception, I can't get the status code.

Page page = null;
try {
    page = webClient.getPage(requestSettings);
    System.out.println(page.getWebResponse().getStatusCode()); // it doesn't go to this line because exception is already thrown
} catch (Exception e) {
    System.out.println(page.getWebResponse().getStatusCode()); // it will fail because of NullPointerException
    System.out.println(e);
}

The following method seems to work only on older versions of HtmlUnit. I'm using v2.25 and the method doesn't exist.

webClient.setThrowExceptionOnFailingStatusCode(false);

Solution

  • The new API now has WebClientOptions,

    you should use:

    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);