I have some java code which checks a http response. Now, I would like to check the code against the client error (4xx) family, how can I do that?
int responseCode = ab.sendGetRequest(href);
The simplest solution would be:
if (400 <= responseCode && responseCode < 500 ){
//...
}
or a bit nicer in terms of coding conventions but giving readability a big hit:
if (HttpStatus.SC_BAD_REQUEST <= responseCode &&
responseCode < HttpStatus.SC_INTERNAL_SERVER_ERROR)
How can I check responseCode
against the 4xx
family somehow like the following...
CLIENT_ERROR.contains(code)
The important point is, that I don't want to use a custom solution (writing my own CLIENT_ERROR
or check against a range,...). Isn't there an according Class in java already present for this purpose?
Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.
4xx client error – the request contains bad syntax or cannot be fulfilled. 5xx server error – the server failed to fulfil an apparently valid request.
If using Spring you can simply do :
HttpStatus.valueOf(statusCode).is4xxClientError()
You can also look at is4xxClientError() implementation if you need anything extra
I'm actually utilizing javax.ws.rs.core.Response.Status.Family
now. Thank you @Kon for the useful hint!
import javax.ws.rs.core.Response.Status.Family;
if (Family.familyOf(responseCode) == Family.CLIENT_ERROR) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With