1. Introduction

*Enum*s provide a powerful way to define a set of named constants in the Java programming language. These are useful for representing fixed sets of related values, such as HTTP status codes. As we know, all web servers on the Internet issue HTTP status codes as standard response codes.

In this tutorial, we’ll delve into creating a Java enum that includes all the HTTP status codes.

2. Understanding HTTP Status Codes

HTTP status codes play a crucial role in web communication by informing clients of the results of their requests. Furthermore, servers issue these three-digit codes, which fall into five categories, each serving a specific function in the HTTP protocol.

3. Benefits of Using Enums for HTTP Status Codes

Enumerating HTTP status codes in Java offers several advantages, including:

  • Type Safety: using enum ensures type safety, making our code more readable and maintainable
  • Grouped Constants: Enums group related constants together, providing a clear and structured way to handle fixed sets of values
  • Avoiding Hardcoded Values: defining HTTP status codes as enum helps prevent errors from hardcoded strings or integers
  • Enhanced Clarity and Maintainability: this approach promotes best practices in software development by enhancing clarity, reducing bugs, and improving code maintainability

4. Basic Approach

To effectively manage HTTP status codes in our Java applications, we can define an enum that encapsulates all standard HTTP status codes and their descriptions.

This approach allows us to leverage the benefits of enum, such as type safety and code clarity. Let’s start by defining the HttpStatus enum:

public enum HttpStatus {
    CONTINUE(100, "Continue"),
    SWITCHING_PROTOCOLS(101, "Switching Protocols"),
    OK(200, "OK"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    MULTIPLE_CHOICES(300, "Multiple Choices"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    NOT_IMPLEMENTED(501, "Not Implemented"),
    BAD_GATEWAY(502, "Bad Gateway"),
    UNKNOWN(-1, "Unknown Status");

    private final int code;
    private final String description;

    HttpStatus(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public static HttpStatus getStatusFromCode(int code) {
        for (HttpStatus status : HttpStatus.values()) {
            if (status.getCode() == code) {
                return status;
            }
        }
        return UNKNOWN;
    }

    public int getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }
}

Each constant in this Enum is associated with an integer code and a string description. Moreover, the constructor initializes these values, and we provide getter methods to retrieve them.

Let’s create unit tests to ensure our HttpStatus Enum class works correctly:

@Test
public void givenStatusCode_whenGetCode_thenCorrectCode() {
    assertEquals(100, HttpStatus.CONTINUE.getCode());
    assertEquals(200, HttpStatus.OK.getCode());
    assertEquals(300, HttpStatus.MULTIPLE_CHOICES.getCode());
    assertEquals(400, HttpStatus.BAD_REQUEST.getCode());
    assertEquals(500, HttpStatus.INTERNAL_SERVER_ERROR.getCode());
}

@Test
public void givenStatusCode_whenGetDescription_thenCorrectDescription() {
    assertEquals("Continue", HttpStatus.CONTINUE.getDescription());
    assertEquals("OK", HttpStatus.OK.getDescription());
    assertEquals("Multiple Choices", HttpStatus.MULTIPLE_CHOICES.getDescription());
    assertEquals("Bad Request", HttpStatus.BAD_REQUEST.getDescription());
    assertEquals("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR.getDescription());
}

Here, we verify that the getCode() and getDescription() methods return the correct values for various HTTP status codes. The first test method checks if the getCode() method returns the correct integer code for each enum constant. Similarly, the second test method ensures the getDescription() method returns the appropriate string description.

5. Using Apache HttpComponents

Apache HttpComponents is a popular library for HTTP communication. To use it with Maven, we include the following dependency in our pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version>
</dependency>

We can find more details about this dependency on Maven Central.

We can use our HttpStatus enum to handle HTTP responses:

@Test
public void givenHttpRequest_whenUsingApacheHttpComponents_thenCorrectStatusDescription() throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet request = new HttpGet("http://example.com");
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        String reasonPhrase = response.getStatusLine().getReasonPhrase();
        assertEquals("OK", reasonPhrase);
    }
}

Here, we start by creating a CloseableHttpClient instance using the createDefault() method. Moreover, this client is responsible for making HTTP requests. We then construct an HTTP GET request to http://example.com with new HttpGet(“http://example.com”). By executing the request with the execute() method, we receive a CloseableHttpResponse object.

*From this response, we extract the status code using response.getStatusLine().getStatusCode().* We then use HttpStatusUtil.getStatusDescription() to retrieve the status description associated with the status code.

Finally, we use assertEquals() to ensure that the description matches the expected value, verifying that our status code handling is accurate.

6. Using RestTemplate Framework

Spring Framework’s RestTemplate can also benefit from our HttpStatus enum for handling HTTP responses. Let’s first include the following dependency in our pom.xml:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>6.1.11</version>
</dependency>

We can find more details about this dependency on Maven Central.

Let’s explore how we can utilize this approach with a simple implementation:

@Test
public void givenHttpRequest_whenUsingSpringRestTemplate_thenCorrectStatusDescription() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity("http://example.com", String.class);
    int statusCode = response.getStatusCode().value();
    String statusDescription = HttpStatus.getStatusFromCode(statusCode).getDescription();
    assertEquals("OK", statusDescription);
}

Here, we create a RestTemplate instance to perform an HTTP GET request. *After obtaining the ResponseEntity object, we extract the status code using response.getStatusCode().value().* We then pass this status code to HttpStatus.getStatusFromCode.getDescription() to retrieve the corresponding status description.

7. Using OkHttp Library

OkHttp is another widely-used HTTP client library in Java. Let’s incorporate this library into the Maven project by adding the following dependency to our pom.xml:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>

We can find more details about this dependency on Maven Central.

Now, let’s integrate our HttpStatus enum with OkHttp to handle responses:

@Test
public void givenHttpRequest_whenUsingOkHttp_thenCorrectStatusDescription() throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
      .url("http://example.com")
      .build();
    try (Response response = client.newCall(request).execute()) {
        int statusCode = response.code();
        String statusDescription = HttpStatus.getStatusFromCode(statusCode).getDescription();
        assertEquals("OK", statusDescription);
    }
}

In this test, we initialize an OkHttpClient instance and create an HTTP GET request using Request.Builder(). We then execute the request with the client.newCall(request).execute() method and obtain the Response object. We extract the status code using the response.code() method and pass it to the HttpStatus.getStatusFromCode.getDescription() method to get the status description.

8. Conclusion

In this article, we discussed using Java enum to represent HTTP status codes, enhancing code readability, maintainability, and type safety.

Whether we opt for a simple enum definition or use it with various Java libraries like Apache HttpComponents, Spring RestTemplate Framework, or OkHttp, Enums are robust enough to handle fixed sets of related constants in Java.

As usual, we can find the full source code and examples over on GitHub.