sandalone
sandalone

Reputation: 41749

Is there any built in class with HTTP response codes and its categories?

When I need to check if a response code is one of success codes (2xx), then I usually create a integer array and look thru it. For example,

public static final int[] SUCCESS_STATUS_CODES = new int[]{
        200, 201, 202, 203, 204, 205, 206, 207, 208, 226
};

I do the same for other response codes.

I was wondering if there is a built-in object which already holds all these codes and regularly updates them which I can use?

For example,

//pseudo code
if(responseCode is from success 2xx category)
   do something
else if (responseCode is from error 4xx category
   do something

Upvotes: 1

Views: 4548

Answers (3)

Vishal_Kotecha
Vishal_Kotecha

Reputation: 491

Bit late to the part but I would like to extend Jaxon's message:

    int responseCode = 200;
    HttpStatus httpStatus = HttpStatus.valueOf(responseCode);
    if (httpStatus.is2xxSuccessful())
    {
      // do something
    }

Upvotes: 1

Jaxon
Jaxon

Reputation: 345

org.springframework.http.HttpStatus has a method HttpStatus.is2xxSuccessful() returns a boolean. It's part of Spring, not built into Java, but hopefully will still be useful to some people.

Upvotes: 5

John Bollinger
John Bollinger

Reputation: 180048

As far as I know, there is no such class in the standard library. The closest I know if is java.net.HttpURLConnection, which provides static constants for the various codes.

But you seem to be going to more work than you need to do. HTTP response code categories are built into their values. You should be able to do something along these lines:

switch (responseCode / 100) {
    case 1:
        /* informational response */
        break;
    case 2:
        /* success response */
        break;
    case 3:
        /* redirection response */
        break;
    case 4:
        /* client error response */
        break;
    case 5:
        /* server error response */
        break;
    default:
        /* bad response code */
        break;
}

Upvotes: 2

Related Questions