Java HTTP Client
In this page:
HttpClient Introduction
Java 11 introduced a modern HttpClient class built for today's web. It replaces the older, clunkier HttpURLConnection and supports both HTTP/1.1 and HTTP/2 seamlessly, including features like connection reuse and server push that the old API never handled well.
Example: HttpClient Introduction
import java.net.http.HttpClient;
public class Main {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient(); // supports HTTP/1.1 and HTTP/2
System.out.println(client.version());
}
}
Login to try C/C++/Java/PHP code in the editor
HttpRequest and HttpResponse
You build outgoing requests using the fluent HttpRequest.Builder API and parse responses using BodyHandlers, such as ofString() for text or ofInputStream() for streaming large payloads. This builder pattern replaces the awkward, mutable connection objects the old HttpURLConnection API forced you to configure.
Example: HttpRequest and HttpResponse
import java.net.http.HttpRequest;
import java.net.URI;
public class Main {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
System.out.println(request.method() + " " + request.uri());
}
}
Login to try C/C++/Java/PHP code in the editor
Asynchronous HTTP Requests
You can send HTTP requests asynchronously using sendAsync() instead of the blocking send(). This method returns a CompletableFuture immediately, letting your application continue other work while the network call completes in the background rather than freezing a thread on I/O.
Example: Asynchronous HTTP Requests
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "response body"); // like sendAsync() returning immediately
System.out.println(future.get());
}
}
Login to try C/C++/Java/PHP code in the editor
POST Requests with BodyPublishers
To send a POST request, use a BodyPublisher to define what goes in the request body -- for example, ofString() to send a JSON string directly, or ofFile() to stream a file's contents without loading it entirely into memory first.
Example: POST Requests with BodyPublishers
import java.net.http.HttpRequest;
import java.net.URI;
public class Main {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
.build();
System.out.println(request.method() + " body publisher attached");
}
}
Login to try C/C++/Java/PHP code in the editor
Managing Headers and Timeouts
You can add standard headers (like Content-Type or Authorization) directly on your request builder, and set connection or request timeouts to avoid a slow or unresponsive server hanging your application indefinitely.
Example: Managing Headers and Timeouts
import java.net.http.HttpRequest;
import java.net.URI;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(5))
.build();
System.out.println(request.headers().firstValue("Content-Type").get());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: