java.net.http.HttpClient
Send synchronous requests.
The Modern HTTP Client
Since Java 11, the JDK ships a modern HTTP client in the java.net.http package. It replaces the old HttpURLConnection with a clean, fluent API that supports HTTP/1.1 and HTTP/2.
The three core types are:
- HttpClient — sends requests and manages config (timeouts, proxies, redirects).
- HttpRequest — an immutable description of what to send.
- HttpResponse — the result, including status, headers, and body.
Creating an HttpClient
You build a client with the static newBuilder() method. A single client can be reused for many requests, and it is thread-safe.
Here we configure HTTP/2 and a connect timeout. newHttpClient() is also available for a quick default instance.
import java.net.http.HttpClient;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
System.out.println("Client version: " + client.version());
}
}All lessons in this course
- java.net.http.HttpClient
- Async Requests
- Request Bodies and Headers
- Handling Responses