Java HTTP Client
In this page:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("url"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
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 so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
// Print a line to the console
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 so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
.build();
// Print a line to the console
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 so it can be used by its short name
import java.net.http.HttpRequest;
// Import java.net.URI so it can be used by its short name
import java.net.URI;
import java.time.Duration;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
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();
// Print a line to the console
System.out.println(request.headers().firstValue("Content-Type").get());
}
}
Login to try C/C++/Java/PHP code in the editor
- Assuming a 404 or 500 response throws an exception, when
HttpClientreturns it normally and you must checkresponse.statusCode(). - Not setting a timeout on the request, so a slow server can block the program.
- Forgetting that
sendAsyncreturns aCompletableFuture, so calling nothing likejoin()letsmainfinish before the response arrives.
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: