In Java 11, a new HTTP client API was introduced as an experimental feature, and it became a standard feature in Java 11. This new API provides a more efficient and easy-to-use alternative to the traditional HttpURLConnection API. In this article, we’ll take a closer look at the Java 11 HTTP client API and provide examples of how to use it.
Creating an HTTP Request
To create an HTTP request using the Java 11 HTTP client API, we first need to create an instance of the HttpClient
class:
HttpClient httpClient = HttpClient.newHttpClient();
We can then use the HttpClient
object to create an HTTP request by creating an instance of the HttpRequest
class. The HttpRequest
class provides several methods for specifying the request method, URL, headers, and body:
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")) .GET() .build();
In this example, we’re creating an HTTP GET request to the URL "https://jsonplaceholder.typicode.com/posts/1"
.
Sending an HTTP Request
Once we’ve created an HTTP request, we can send it using the HttpClient
object:
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
In this example, we’re sending the HTTP request and getting a response as a String
using the HttpResponse.BodyHandlers.ofString()
method. The HttpClient.send()
method is a blocking call, so it will wait for the server to respond before continuing.
Handling an HTTP Response
After we’ve sent an HTTP request, we can handle the response by examining the HttpResponse
object:
int statusCode = response.statusCode(); String responseBody = response.body();
In this example, we’re getting the status code and response body of the HTTP response. We can also examine the headers of the response using the headers()
method:
Map<String, List<String>> headers = response.headers().map();
Handling Errors
If an HTTP request fails, an exception will be thrown. We can handle these exceptions using a try-catch block:
try { HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); } catch (IOException | InterruptedException e) { // Handle the exception }
In this example, we’re handling the IOException
and InterruptedException
exceptions that can be thrown when sending an HTTP request.
Setting Request Timeouts
We can set timeouts for HTTP requests by specifying the connectTimeout()
and timeout()
methods when creating the HttpClient
object:
HttpClient httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .timeout(Duration.ofSeconds(30)) .build();
In this example, we’re setting a 10-second timeout for connecting to the server and a 30-second timeout for receiving a response from the server.
Post Example
Here’s an another example of how to use the Java 11 HTTP client API to make a POST request:
HttpClient httpClient = HttpClient.newHttpClient(); // Create the HTTP request HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/posts")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}")) .build(); // Send the HTTP request and get the response asynchronously CompletableFuture<HttpResponse<String>> responseFuture = httpClient.sendAsync(request, BodyHandlers.ofString()); // Handle the response asynchronously responseFuture.thenAccept(response -> { int statusCode = response.statusCode(); String responseBody = response.body(); System.out.println("Status code: " + statusCode); System.out.println("Response body: " + responseBody); }); // Wait for the response to complete responseFuture.join();
In this example, we’re making a POST request to the URL "https://jsonplaceholder.typicode.com/posts"
with the JSON payload {"title":"foo","body":"bar","userId":1}
. We’re setting the "Content-Type"
header to "application/json"
to indicate that we’re sending JSON data in the request body.
We’re using the HttpClient.sendAsync()
method to send the HTTP request asynchronously, and we’re handling the response asynchronously using a CompletableFuture
.
Once the response is received, we’re getting the status code and response body using the HttpResponse
object and printing them to the console.
This example demonstrates how to use the Java 11 HTTP client API to make a POST request with a JSON payload. You can modify the URL, headers, and request body to make different types of POST requests.
The Java 11 HTTP client API provides a more efficient and easy-to-use alternative to the traditional HttpURLConnection API. In this article, we’ve looked at how to create an HTTP request, send it, handle the response, handle errors, and set timeouts using the Java 11 HTTP client API. By using this API, developers can write more efficient and maintainable code when working with HTTP requests in Java.