The java.net.http.HttpClient (introduced in Java 11) provides a modern, fluent API to send synchronous and asynchronous HTTP requests. It completely replaces the legacy and cumbersome HttpURLConnection.
Interactions with this API revolve around three core classes from the java.net.http package: HttpClient, HttpRequest, and HttpResponse. Prerequisites
Ensure you import the core networking and HTTP classes into your Java file:
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; Use code with caution. 1. Sending a GET Request
A GET request retrieves data from a designated server. Building the request uses a factory .GET() method, which is applied by default even if omitted.
public static void sendGetRequest() throws Exception { // 1. Create the HttpClient instance HttpClient client = HttpClient.newHttpClient(); // 2. Build the GET request HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(”https://typicode.com”)) .GET() // Optional default method .header(“Accept”, “application/json”) .build(); // 3. Send the request and handle the string response HttpResponse Use code with caution. 2. Sending a POST Request
A POST request transmits payload data (often structured as JSON) to create or update an existing server resource. You must specify a BodyPublisher to format the request payload. Sending HTTP POST Request In Java – Stack Overflow
Leave a Reply