简体   繁体   中英

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?

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 using Spring you can simply do :

    HttpStatus.valueOf(statusCode).is4xxClientError()

You can also look at is4xxClientError() implementation if you need anything extra

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM