Java’s HTTP client API was introduced in Java 11 as a replacement for the legacy HttpURLConnection
API. The new API provides a more modern, easy-to-use interface for sending HTTP requests and handling responses.
Creating an HTTP Client
To use the HTTP client API, you first need to create an instance of the HttpClient
class. Here’s an example:
HttpClient client = HttpClient.newHttpClient();
This creates a new HTTP client with default settings. You can customize the client by passing in a HttpClient.Builder
object to the newHttpClient()
method.
Sending a GET Request
To send a GET request using the HTTP client API, you first need to create an instance of the HttpRequest
class. Here’s an example:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api/data"))
.build();
This creates a new GET request for the URL https://example.com/api/data
. You can customize the request by calling methods on the HttpRequest.Builder
object.
Next, you can send the request using the send()
method of the HTTP client:
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
This sends the request and blocks until a response is received. The response is returned as an HttpResponse
object, which contains the response status code, headers, and body.
In this example, we’re using the BodyHandlers.ofString()
method to specify that the response body should be returned as a String
. Other BodyHandlers
are available to handle different response types.
Sending a POST Request
Sending a POST request is similar to sending a GET request, but you need to include a request body. Here’s an example:
String requestBody = "param1=value1¶m2=value2";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api/data"))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
This creates a new POST request for the URL https://example.com/api/data
with the request body param1=value1¶m2=value2
.
Handling Responses
Once you have an HttpResponse
object, you can access the response status code, headers, and body:
int statusCode = response.statusCode();
Map<String, List<String>> headers = response.headers().map();
String responseBody = response.body();
If the response body is a JSON object, you can parse it using a JSON library like Jackson or Gson:
ObjectMapper objectMapper = new ObjectMapper();
MyResponseObject responseObject = objectMapper.readValue(responseBody, MyResponseObject.class);
Error Handling
When sending an HTTP request, there’s always a chance that an error will occur. The HTTP client API provides several ways to handle errors.
First, you can check the response status code to see if the request was successful:
if (response.statusCode() == 200) {
// Request was successful
} else {
// Request failed
}
You can also catch exceptions thrown by the send()
method:
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException | InterruptedException e) {
// Error occurred
}
Conclusion
Java’s HTTP client API provides a modern, easy-to-use interface for sending HTTP requests and handling responses. With support for asynchronous requests, request and response streaming, and more, it’s a powerful tool for building web applications in Java.