Package java.net.http

Class HttpClient

java.lang.Object
java.net.http.HttpClient
All Implemented Interfaces:
AutoCloseable

public abstract class HttpClient extends Object implements AutoCloseable
An HTTP Client.

An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder. The newBuilder method returns a builder that creates instances of the default HttpClient implementation. The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc. Once built, an HttpClient is immutable, and can be used to send multiple requests.

An HttpClient provides configuration information, and resource sharing, for all requests sent through it. An HttpClient instance typically manages its own pools of connections, which it may then reuse as and when necessary. Connection pools are typically not shared between HttpClient instances. Creating a new client for each operation, though possible, will usually prevent reusing such connections.

A BodyHandler must be supplied for each HttpRequest sent. The BodyHandler determines how to handle the response body, if any. Once an HttpResponse is received, the headers, response code, and body (typically) are available. Whether the response body bytes have been read or not depends on the type, T, of the response body.

Requests can be sent either synchronously or asynchronously:

  • send(HttpRequest, BodyHandler) blocks until the request has been sent and the response has been received.
  • sendAsync(HttpRequest, BodyHandler) sends the request and receives the response asynchronously. The sendAsync method returns immediately with a CompletableFuture<HttpResponse>. The CompletableFuture completes when the response becomes available. The returned CompletableFuture can be combined in different ways to declare dependencies among several asynchronous tasks.

Synchronous Example

HttpClient client = HttpClient.newBuilder()
     .version(Version.HTTP_1_1)
     .followRedirects(Redirect.NORMAL)
     .connectTimeout(Duration.ofSeconds(20))
     .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
     .authenticator(Authenticator.getDefault())
     .build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());

Asynchronous Example

 HttpRequest request = HttpRequest.newBuilder()
     .uri(URI.create("https://foo.com/"))
     .timeout(Duration.ofMinutes(2))
     .header("Content-Type", "application/json")
     .POST(BodyPublishers.ofFile(Paths.get("file.json")))
     .build();
client.sendAsync(request, BodyHandlers.ofString())
     .thenApply(HttpResponse::body)
     .thenAccept(System.out::println);

Security checks

If a security manager is present then security checks are performed by the HTTP Client's sending methods. An appropriate URLPermission is required to access the destination server, and proxy server if one has been configured. The form of the URLPermission required to access a proxy has a method parameter of "CONNECT" (for all kinds of proxying) and a URL string of the form "socket://host:port" where host and port specify the proxy's address.

API Note:
Resources allocated by the HttpClient may be reclaimed early by closing the client.
Implementation Note:

The JDK built-in implementation of the HttpClient overrides close(), shutdown(), shutdownNow(), awaitTermination(Duration), and isTerminated() to provide a best effort implementation. Failing to close, cancel, or read returned streams to exhaustion, such as streams provided when using HttpResponse.BodyHandlers.ofInputStream(), HttpResponse.BodyHandlers.ofLines(), or HttpResponse.BodyHandlers.ofPublisher(), may prevent requests submitted before an orderly shutdown to run to completion. Likewise, failing to request data or cancel subscriptions from a custom BodySubscriber may stop delivery of data and stall an orderly shutdown.

If an explicit executor has not been set for an HttpClient, and a security manager has been installed, then the default executor will execute asynchronous and dependent tasks in a context that is granted no permissions. Custom request body publishers, response body handlers, response body subscribers, and WebSocket Listeners, if executing operations that require privileges, should do so within an appropriate privileged context.

Since:
11