Whether you are new to Java programming or looking to upgrade your skills, this beginner’s guide will provide you with a comprehensive overview of the new HTTP Client API in java 21 and how to implement it in your projects.
From setting up the environment to making GET and POST requests, this tutorial will walk you through the essential steps to utilize this powerful new feature in Java 21.
By the end of this guide, you will have the knowledge and confidence to incorporate the new HTTP Client API into your Java applications effectively.

Understanding HTTP Client API Fundamentals

The new HTTP Client API in Java 21 provides a powerful and flexible way to make HTTP requests and handle responses.
This section will cover the fundamentals of the HTTP Client API, including the types of requests it supports and its underlying architecture.

Types of HTTP Requests and How to Handle Them

When using the HTTP Client API, you can make various types of requests, such as GET, POST, PUT, DELETE, and more.
Each type of request serves a different purpose, and it’s essential to understand how to handle them effectively.

Here’s a code sample demonstrating how to make a simple GET request using the HTTP Client API:

// Create and send a GET request
HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("https://api.example.com/data"))
    .GET()
    .build();
HttpResponse response = HttpClient
                        .newHttpClient()
                        .send(request, 
                        HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

This code snippet demonstrates how to make a basic GET request and handle the response.
It’s crucial to understand how to handle different types of requests to interact with web services effectively.
Importantly, the HTTP Client API also supports handling asynchronous requests, which can improve the performance of your applications.

The HTTP Client API’s Architecture

One of the key features of the HTTP Client API is its modular and extensible architecture.

The API is designed to be flexible and customizable, allowing developers to adapt it to their specific needs.
Here’s a code sample that demonstrates how to customize the HTTP Client’s configuration:

// Create a custom HTTP Client with timeouts and custom SSLContext
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
HttpClient customClient = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(10))
    .sslContext(sslContext)
    .build();

One of the key factors that sets the HTTP Client API apart is its modular and extensible architecture, which allows developers to customize and adapt it to their specific use cases.
The API is designed to provide a high degree of control over the HTTP request and response handling process, making it a powerful tool for building robust and efficient networked applications. The flexibility of the API’s architecture allows for seamless integration with various authentication mechanisms, cookie policies, and connection pooling strategies, providing developers with the necessary tools to build performant and secure networking solutions. It also supports different types of requests, including synchronous and asynchronous requests, enabling developers to leverage the full capabilities of modern networking protocols.

Step-by-Step Guide to Using Java 21’s HTTP Client

If you’re looking to leverage the new HTTP Client API in Java 21, you’ve come to the right place.
This guide will walk you through everything you need to know to start using Java 21’s HTTP Client to make and process HTTP requests and responses.

Setting Up Your Development Environment

Step by Step, let’s start by setting up your development environment for using Java 21’s HTTP Client.
The first thing you need to do is ensure that you have Java 21 installed on your system.
You can check this by running the following command in your terminal or command prompt:

java -version

You should get something like

openjdk version "21.0.1" 2023-10-17
OpenJDK Runtime Environment (build 21.0.1+12-29)
OpenJDK 64-Bit Server VM (build 21.0.1+12-29, mixed mode, sharing)

Once you have confirmed that you have Java 21 installed, you can create a new Java project in your favorite IDE and start learning the new HTTP client.

Sending HTTP Requests

In Java 21, you can create a simple HTTP request using the HttpRequest class:

HttpRequest request = HttpRequest.newBuilder()
        .uri(
         URI.create("https://jsonplaceholder.typicode.com/posts"))
        .GET()
        .build();

In this code snippet, we are creating a GET request to a fake web service.
This is just a basic example, but you can also add headers, a request body, and more to your HTTP request.

Adding Headers

You can add headers to your request using the following code:

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.example.com/data"))
        .header("Authorization", "Bearer token")
        .GET()
        .build();

Setting the HTTP Version

HTTP Client in java 21 allows you to set the protocol version based on factors such as server compatibility, performance requirements, and the features supported by different protocol versions.

Assume that the server you are communicating with supports HTTP/2 for better performance and efficiency.

To set the protocol version, you can use the version() method on the Builder class and pass the desired HTTP version as an argument.

HttpClient client = HttpClient.newBuilder()
    .version(Version.HTTP_2)
    .build();

Receiving and Processing HTTP Responses

One of the vital parts of using the HTTP Client API is receiving and processing HTTP responses.
Once you have sent an HTTP request, you can use the HttpResponse class to receive and process the response:

HttpResponse response = client.send(
                               request, 
                               HttpResponse.BodyHandlers.ofString());

For instance, you can access the status code and response body of the HTTP response using the following code:

int statusCode = response.statusCode();
String responseBody = response.body();

Complete HTTP Client Example

Below is a complete example of Http Client in java 21 that builds a client, creates a request, sends it and reads the response.

HttpRequest request = HttpRequest.newBuilder()
		        .uri(
                         URI.create("https://jsonplaceholder.typicode.com/posts"))
		        .GET()
		        .build();
HttpClient client = HttpClient.newBuilder()
		    .version(Version.HTTP_2)
		    .build();
try {
  HttpResponse<String> response = client.send(request, 
                                          HttpResponse.BodyHandlers.ofString());
  String body = response.body();
  System.out.println(body);
} catch (IOException e) {
  e.printStackTrace();
} catch (InterruptedException e) {
  e.printStackTrace();
}

HTTP POST Request

You can also write a POST request with HTTP client in java 21 using POST() method and supplying it request body as shown below

HttpRequest request = HttpRequest.newBuilder()
		      .uri(
                       URI.create("http://jsonplaceholder.typicode.com/posts"))
		      .POST(
                       HttpRequest.BodyPublishers.ofString("{\"title\":\"Test\"}"))
		      .build();

Asynchronous Calls

Java 21 HTTP client can be used to make asynchronous calls to an endpoint URL.

Asynchronous means non-blocking, which do not wait for the call to return and proceed further.
This can be done using sendAsync() method, which returns a CompletableFuture as shown below.

// Asynchronous HTTP GET request
CompletableFuture future = client
                           .sendAsync(request, 
                            BodyHandlers.ofString())
                           .thenApply(HttpResponse::body);

For using asynchronous HTTP requests, you need to ensure below points:

  • Proper thread management is essential for efficient asynchronous calls.
  • Ensure callback handlers are implemented effectively for handling asynchronous request completion or failure.
  • Manage error propagation to handle exceptions and ensure correct propagation within the application.

After considering these factors, the HTTP Client API can be used efficiently for making asynchronous calls without compromising application stability.

Hope the article was informative and useful !