Java 11 introduced the HttpClient
API to simplify and modernize HTTP communications. This API supports sending requests using different HTTP methods (GET, POST, PUT, DELETE, etc.). Below is an explanation and example of how to perform these operations.
1. Setup
You will use the HttpClient
and related classes from java.net.http
package:
HttpClient
– To execute HTTP requests.HttpRequest
– To construct and describe HTTP requests.HttpResponse
– To handle HTTP responses.
2. Example Code
Here’s how you can send HTTP requests with different methods using HttpClient
in Java 11.
package org.kodejava.net.http;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
public class HttpClientMethodExample {
public static void main(String[] args) {
try {
// Create an HttpClient instance
HttpClient httpClient = HttpClient.newHttpClient();
// Example: GET Request
HttpRequest getRequest = HttpRequest.newBuilder()
.uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
.GET() // Default is GET, this is optional
.build();
HttpResponse<String> getResponse = httpClient.send(getRequest, BodyHandlers.ofString());
System.out.println("GET Response: " + getResponse.body());
// Example: POST Request
HttpRequest postRequest = HttpRequest.newBuilder()
.uri(new URI("https://jsonplaceholder.typicode.com/posts"))
.POST(BodyPublishers.ofString("{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"))
.header("Content-Type", "application/json")
.build();
HttpResponse<String> postResponse = httpClient.send(postRequest, BodyHandlers.ofString());
System.out.println("POST Response: " + postResponse.body());
// Example: PUT Request
HttpRequest putRequest = HttpRequest.newBuilder()
.uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
.PUT(BodyPublishers.ofString("{\"id\":1,\"title\":\"updated\",\"body\":\"new content\",\"userId\":1}"))
.header("Content-Type", "application/json")
.build();
HttpResponse<String> putResponse = httpClient.send(putRequest, BodyHandlers.ofString());
System.out.println("PUT Response: " + putResponse.body());
// Example: DELETE Request
HttpRequest deleteRequest = HttpRequest.newBuilder()
.uri(new URI("https://jsonplaceholder.typicode.com/posts/1"))
.DELETE()
.build();
HttpResponse<String> deleteResponse = httpClient.send(deleteRequest, BodyHandlers.ofString());
System.out.println("DELETE Response Code: " + deleteResponse.statusCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Explanation
HttpClient
Creation: TheHttpClient
instance is reusable for making multiple requests.- GET Request:
- Use
.GET()
method to send a GET request. - Response is parsed as a String using
BodyHandlers.ofString()
.
- Use
- POST Request:
- Use
.POST(BodyPublishers.ofString(content))
to send a POST request with a payload. - Set the
Content-Type
header for JSON or other content types.
- Use
- PUT Request:
- Use
.PUT(BodyPublishers.ofString(content))
for PUT requests with a payload. - Similar to POST, set the proper headers.
- Use
- DELETE Request:
- Use
.DELETE()
to send DELETE requests. - Rarely includes a body; that’s why no publisher is used.
- Use
- Error Handling:
- Be sure to include error handling for exceptions such as
IOException
andInterruptedException
.
- Be sure to include error handling for exceptions such as
4. Output Example
If you run the code using the example endpoints, the output might look something like this:
GET Response: {
"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"
}
POST Response: {
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}
PUT Response: {
"id": 1,
"title": "updated",
"body": "new content",
"userId": 1
}
DELETE Response Code: 200
5. Notes
- You’ll need an API endpoint that supports CRUD operations for realistic testing.
- Avoid hardcoding URIs in production; keep them configurable.
- Handle response status codes appropriately for error cases (like 404, 500).
This approach provides a clean and modern way to work with HTTP in Java!