Introduction
Java 11 introduced a new HTTP client API to handle HTTP requests and responses in a more flexible and efficient manner. The new HTTP client API is part of the java.net.http
package, providing a modern and easy-to-use API to perform HTTP operations. It supports both synchronous and asynchronous communication, making it versatile for various use cases.
Key Features:
- HTTP/2 Support: The HTTP client supports HTTP/2, which provides better performance and efficiency over HTTP/1.1.
- Synchronous and Asynchronous Requests: You can perform both synchronous and asynchronous HTTP requests.
- Improved API: The new API is more intuitive and easier to use compared to the old
HttpURLConnection
.
In this guide, we will use the HTTP client to make HTTP requests to a dummy API and handle responses.
Setting Up the HTTP Client
To use the Java HTTP client, you need to import the java.net.http
package and create an instance of HttpClient
.
Creating an HTTP Client
import java.net.http.HttpClient;
public class HttpClientExample {
public static void main(String[] args) {
// Create an instance of HttpClient
HttpClient client = HttpClient.newHttpClient();
}
}
Making an HTTP GET Request
Let’s make an HTTP GET request to a public dummy API and handle the response. We will use the jsonplaceholder.typicode.com
API, which provides sample data for testing and prototyping.
Example: HTTP GET Request
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
public class HttpClientGetExample {
public static void main(String[] args) {
// Create an instance of HttpClient
HttpClient client = HttpClient.newHttpClient();
// Create an HTTP GET request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build();
// Send the request and receive the response
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Print the response status code and body
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Response Code: 200
Response Body: {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Explanation:
- HttpClient: An instance of
HttpClient
is created to handle the HTTP request. - HttpRequest: The
HttpRequest
is built usingHttpRequest.newBuilder()
with the URI of the dummy API endpoint. TheGET()
method specifies that this is a GET request. - HttpResponse: The request is sent using
client.send()
, and the response is received as aString
usingHttpResponse.BodyHandlers.ofString()
. - Response Handling: The response status code and body are printed to the console.
Making an HTTP POST Request
Next, let’s make an HTTP POST request to the same dummy API to send some data. We will use the /posts
endpoint, which accepts JSON data.
Example: HTTP POST Request
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
public class HttpClientPostExample {
public static void main(String[] args) {
// Create an instance of HttpClient
HttpClient client = HttpClient.newHttpClient();
// Define the JSON data to be sent in the POST request
String json = """
{
"title": "foo",
"body": "bar",
"userId": 1
}
""";
// Create an HTTP POST request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.POST(HttpRequest.BodyPublishers.ofString(json))
.header("Content-Type", "application/json")
.build();
// Send the request and receive the response
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Print the response status code and body
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Response Code: 201
Response Body: {
"id": 101,
"title": "foo",
"body": "bar",
"userId": 1
}
Explanation:
- JSON Data: A JSON string is defined to be sent in the POST request body.
- HttpRequest: The
HttpRequest
is built with thePOST()
method, specifying the JSON data and setting theContent-Type
header toapplication/json
. - Response Handling: The response status code (201 Created) and body are printed to the console, showing that a new resource was successfully created.
Asynchronous HTTP Requests
The Java HTTP client also supports asynchronous requests, allowing you to perform non-blocking operations. This is useful for applications that require high concurrency and responsiveness.
Example: Asynchronous HTTP GET Request
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class AsyncHttpClientExample {
public static void main(String[] args) {
// Create an instance of HttpClient
HttpClient client = HttpClient.newHttpClient();
// Create an HTTP GET request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/2"))
.GET()
.build();
// Send the request asynchronously
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
// Handle the response asynchronously
futureResponse.thenAccept(response -> {
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}).join();
}
}
Output:
Response Code: 200
Response Body: {
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
Explanation:
- CompletableFuture: The
sendAsync()
method returns aCompletableFuture
, allowing the request to be handled asynchronously. - Lambda Expression: The
thenAccept()
method processes the response once it is received, printing the status code and body. - Non-Blocking: The asynchronous approach allows other operations to continue while waiting for the response.
Conclusion
The Java HTTP client introduced in Java 11 provides a powerful and flexible way to handle HTTP requests and responses. With support for both synchronous and asynchronous communication, as well as improved API design, the new HTTP client makes it easier to perform HTTP operations in Java applications.
Summary:
- HTTP/2 Support: The new HTTP client supports HTTP/2, offering better performance.
- Synchronous and Asynchronous Requests: You can perform both blocking and non-blocking HTTP requests.
- Modern API: The new API is more intuitive and easier to use, with support for handling headers, body publishers, and more.
By using the Java HTTP client, you can build robust and efficient applications that interact with web services and APIs seamlessly.