Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for 4xx Http Code with native Java

Tags:

java

http

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?

like image 583
Christoph Avatar asked Jan 13 '16 16:01

Christoph


People also ask

How do I check my HTTP status code?

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.

For what purpose is the 4xx series HTTP status code used for?

4xx client error – the request contains bad syntax or cannot be fulfilled. 5xx server error – the server failed to fulfil an apparently valid request.


2 Answers

If using Spring you can simply do :

    HttpStatus.valueOf(statusCode).is4xxClientError()

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

like image 137
rgrebski Avatar answered Nov 06 '22 05:11

rgrebski


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) {
like image 44
Christoph Avatar answered Nov 06 '22 05:11

Christoph