How do I handle HTTP response status codes with Java 11 HttpClient?

Handling HTTP response status codes with Java 11’s HttpClient API involves making a request, receiving a response, and then checking the status code returned in the response.

Here’s how you can do this:

Steps to Handle HTTP Response Status Codes

  1. Create the HttpClient: Build an instance of HttpClient.
  2. Build the Request: Define the HTTP request (e.g., GET, POST, etc.) with the target URI.
  3. Send the Request: Use HttpClient to send the request and receive an HttpResponse.
  4. Handle the Response: Extract and handle the HTTP response status code from the HttpResponse.

Here’s sample code to demonstrate these steps:

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientExample {
    public static void main(String[] args) {
        // Step 1: Create an HttpClient
        HttpClient client = HttpClient.newHttpClient();

        // Step 2: Build the Request
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")) // Replace with your endpoint
                .GET()
                .build();

        try {
            // Step 3: Send the Request and Receive the Response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // Step 4: Handle the Response Status Code
            int statusCode = response.statusCode();
            if (statusCode >= 200 && statusCode < 300) {
                // Handle successful responses (e.g., HTTP 200 OK)
                System.out.println("Response: " + response.body());
            } else if (statusCode >= 400 && statusCode < 500) {
                // Handle client errors (e.g., HTTP 404 Not Found)
                System.err.println("Client error: " + statusCode);
            } else if (statusCode >= 500) {
                // Handle server errors (e.g., HTTP 500 Internal Server Error)
                System.err.println("Server error: " + statusCode);
            } else {
                // Handle unexpected status codes
                System.err.println("Unexpected response: " + statusCode);
            }
        } catch (Exception e) {
            // Handle Exceptions
            e.printStackTrace();
        }
    }
}

Explanation

  1. HttpClient: The HttpClient is created using HttpClient.newHttpClient().
  2. HttpRequest: Use HttpRequest.Builder to create and configure an HTTP request.
  3. HttpResponse: The client.send() method sends the request and blocks until the response is received.
  4. Status Code Check: The response provides a status code via response.statusCode(). Different ranges of status codes are handled using conditional blocks.

Common HTTP Status Code Ranges

  • 2xx (Success): The request was successfully processed.
  • 3xx (Redirection): The requested resource has been moved.
  • 4xx (Client Errors): The client made an invalid request or the resource was not found.
    • Example: 404 (Not Found), 401 (Unauthorized)
  • 5xx (Server Errors): The server encountered an error while processing the request.
    • Example: 500 (Internal Server Error), 503 (Service Unavailable)

Advanced Handling

Advanced use cases might involve handling:

  • Headers: Access response or set request headers.
  • Timeouts: Set timeouts for requests.
  • Asynchronous Requests: Use HttpClient.sendAsync() for non-blocking requests.

This approach is the standard way to interact with HTTP codes in Java 11+ using the HttpClient API.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.