Christoph Christoph - 2 months ago 23
HTTP Question

check for 4xx Http Code with native Java

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?

Answer

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) {