AutoCloseable
public abstract class HttpClient extends Object implements AutoCloseable
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);
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.
HttpClient
may be reclaimed early by closing the client. 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.
Modifier and Type | Class | Description |
---|---|---|
static interface |
HttpClient.Builder |
A builder of HTTP Clients. |
static enum |
HttpClient.Redirect |
Defines the automatic redirection policy. |
static enum |
HttpClient.Version |
The HTTP protocol version. |
Modifier | Constructor | Description |
---|---|---|
protected |
Creates an HttpClient. |
Modifier and Type | Method | Description |
---|---|---|
abstract Optional |
authenticator() |
Returns an Optional containing the Authenticator set on this client. |
boolean |
awaitTermination |
Blocks until all operations have completed execution after a shutdown request, or the duration elapses, or the current thread is interrupted, whichever happens first. |
void |
close() |
Initiates an orderly shutdown in which requests previously submitted to send or sendAsync are run to completion, but no new request will be accepted. |
abstract Optional |
connectTimeout() |
Returns an Optional containing the connect timeout duration for this client. |
abstract Optional |
cookieHandler() |
Returns an Optional containing this client's CookieHandler . |
abstract Optional |
executor() |
Returns an Optional containing this client's Executor . |
abstract HttpClient.Redirect |
followRedirects() |
Returns the follow redirects policy for this client. |
boolean |
isTerminated() |
Returns true if all operations have completed following a shutdown. |
static HttpClient.Builder |
newBuilder() |
Creates a new HttpClient builder. |
static HttpClient |
newHttpClient() |
Returns a new HttpClient with default settings. |
WebSocket.Builder |
newWebSocketBuilder() |
Creates a new WebSocket builder (optional operation). |
abstract Optional |
proxy() |
Returns an Optional containing the ProxySelector supplied to this client. |
abstract <T> HttpResponse |
send |
Sends the given request using this client, blocking if necessary to get the response. |
abstract <T> CompletableFuture |
sendAsync |
Sends the given request asynchronously using this client with the given response body handler. |
abstract <T> CompletableFuture |
sendAsync |
Sends the given request asynchronously using this client with the given response body handler and push promise handler. |
void |
shutdown() |
Initiates an orderly shutdown in which requests previously submitted with send or sendAsync are run to completion, but no new request will be accepted. |
void |
shutdownNow() |
This method attempts to initiate an immediate shutdown. |
abstract SSLContext |
sslContext() |
Returns this client's SSLContext . |
abstract SSLParameters |
sslParameters() |
Returns a copy of this client's SSLParameters . |
abstract HttpClient.Version |
version() |
Returns the preferred HTTP protocol version for this client. |
protected HttpClient()
public static HttpClient newHttpClient()
HttpClient
with default settings. Equivalent to newBuilder().build()
.
The default settings include: the "GET" request method, a preference of HTTP/2, a redirection policy of NEVER, the default proxy selector, and the default SSL context.
HttpClient
instance is constructed. Changing the system-wide values after an HttpClient
instance has been built, for instance, by calling ProxySelector.setDefault(ProxySelector)
or SSLContext.setDefault(SSLContext)
, has no effect on already built instances.UncheckedIOException
- if necessary underlying IO resources required to build a new HttpClient cannot be allocated.public static HttpClient.Builder newBuilder()
HttpClient
builder. Builders returned by this method create instances of the default HttpClient
implementation.
HttpClient.Builder
public abstract Optional<CookieHandler> cookieHandler()
Optional
containing this client's CookieHandler
. If no CookieHandler
was set in this client's builder, then the Optional
is empty.Optional
containing this client's CookieHandler
public abstract Optional<Duration> connectTimeout()
Optional
containing the connect timeout duration for this client. If the connect timeout duration was not set in the client's builder, then the Optional
is empty.Optional
containing this client's connect timeout durationpublic abstract HttpClient.Redirect followRedirects()
NEVER
.public abstract Optional<ProxySelector> proxy()
Optional
containing the ProxySelector
supplied to this client. If no proxy selector was set in this client's builder, then the Optional
is empty. Even though this method may return an empty optional, the
HttpClient
may still have a non-exposed default proxy selector that is used for sending HTTP requests.
Optional
containing the proxy selector supplied to this client.public abstract SSLContext sslContext()
SSLContext
. If no SSLContext
was set in this client's builder, then the default context is returned.
public abstract SSLParameters sslParameters()
SSLParameters
. If no SSLParameters
were set in the client's builder, then an implementation specific default set of parameters, that the client will use, is returned.
SSLParameters
public abstract Optional<Authenticator> authenticator()
Optional
containing the Authenticator
set on this client. If no Authenticator
was set in the client's builder, then the Optional
is empty.Optional
containing this client's Authenticator
public abstract HttpClient.Version version()
HttpClient.Version.HTTP_2
public abstract Optional<Executor> executor()
Optional
containing this client's Executor
. If no Executor
was set in the client's builder, then the Optional
is empty. Even though this method may return an empty optional, the
HttpClient
may still have an non-exposed default executor that is used for executing asynchronous and dependent tasks.
Optional
containing this client's Executor
public abstract <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) throws IOException, InterruptedException
HttpResponse
<T>
contains the response status, headers, and body ( as handled by given response body handler ). If the operation is interrupted, the default HttpClient
implementation attempts to cancel the HTTP exchange and InterruptedException
is thrown. No guarantee is made as to exactly when the cancellation request may be taken into account. In particular, the request might still get sent to the server, as its processing might already have started asynchronously in another thread, and the underlying resources may only be released asynchronously.
T
- the response body typerequest
- the requestresponseBodyHandler
- the response body handlerIOException
- if an I/O error occurs when sending or receiving, or the client has shut down
InterruptedException
- if the operation is interruptedIllegalArgumentException
- if the request
argument is not a request that could have been validly built as specified by HttpRequest.Builder
.SecurityException
- If a security manager has been installed and it denies access
to the URL in the given request, or proxy if one is configured. See security checks for further information.public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)
Equivalent to: sendAsync(request, responseBodyHandler, null)
.
T
- the response body typerequest
- the requestresponseBodyHandler
- the response body handlerCompletableFuture<HttpResponse<T>>
IllegalArgumentException
- if the request
argument is not a request that could have been validly built as specified by HttpRequest.Builder
.public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler, HttpResponse.PushPromiseHandler<T> pushPromiseHandler)
The returned completable future, if completed successfully, completes with an HttpResponse
<T>
that contains the response status, headers, and body ( as handled by given response body handler ).
Push promises received, if any, are handled by the given pushPromiseHandler
. A null
valued pushPromiseHandler
rejects any push promises.
The returned completable future completes exceptionally with:
IOException
- if an I/O error occurs when sending or receiving, or the client has shut down.SecurityException
- If a security manager has been installed and it denies access
to the URL in the given request, or proxy if one is configured. See security checks for further information. The default HttpClient
implementation returns CompletableFuture
objects that are cancelable. CompletableFuture
objects derived from cancelable futures are themselves cancelable. Invoking cancel(true) on a cancelable future that is not completed, attempts to cancel the HTTP exchange in an effort to release underlying resources as soon as possible. No guarantee is made as to exactly when the cancellation request may be taken into account. In particular, the request might still get sent to the server, as its processing might already have started asynchronously in another thread, and the underlying resources may only be released asynchronously.
T
- the response body typerequest
- the requestresponseBodyHandler
- the response body handlerpushPromiseHandler
- push promise handler, may be nullCompletableFuture<HttpResponse<T>>
IllegalArgumentException
- if the request
argument is not a request that could have been validly built as specified by HttpRequest.Builder
.public WebSocket.Builder newWebSocketBuilder()
WebSocket
builder (optional operation). Example
HttpClient client = HttpClient.newHttpClient();
CompletableFuture<WebSocket> ws = client.newWebSocketBuilder()
.buildAsync(URI.create("ws://websocket.example.com"), listener);
Finer control over the WebSocket Opening Handshake can be achieved by using a custom HttpClient
.
Example
InetSocketAddress addr = new InetSocketAddress("proxy.example.com", 80);
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(addr))
.build();
CompletableFuture<WebSocket> ws = client.newWebSocketBuilder()
.buildAsync(URI.create("ws://websocket.example.com"), listener);
UnsupportedOperationException
. Clients obtained through newHttpClient()
or newBuilder()
return a WebSocket
builder.WebSocket
s created with it operate in a non-blocking fashion. That is, their methods do not block before returning a CompletableFuture
. Asynchronous tasks are executed in this HttpClient
's executor. When a CompletionStage
returned from Listener.onClose
completes, the WebSocket
will send a Close message that has the same code the received message has and an empty reason.
WebSocket.Builder
UnsupportedOperationException
- if this HttpClient
does not provide WebSocket supportpublic void shutdown()
send
or sendAsync
are run to completion, but no new request will be accepted. Running a request to completion may involve running several operations in the background, including waiting for responses to be delivered, which will all have to run to completion until the request is considered completed. Invocation has no additional effect if already shut down. This method does not wait for previously submitted request to complete execution. Use awaitTermination
or close
to do that.
public boolean awaitTermination(Duration duration) throws InterruptedException
duration
elapses, or the current thread is interrupted, whichever happens first. Operations are any tasks required to run a request previously submitted with send
or sendAsync
to completion. This method does not wait if the duration to wait is less than or equal to zero. In this case, the method just tests if the thread has terminated.
duration
- the maximum time to waittrue
if this client terminated and false
if the timeout elapsed before terminationInterruptedException
- if interrupted while waitingpublic boolean isTerminated()
true
if all operations have completed following a shutdown. Operations are any tasks required to run a request previously submitted with send
or sendAsync
to completion. Note that isTerminated
is never true
unless either shutdown
or shutdownNow
was called first.
true
if all tasks have completed following a shutdownpublic void shutdownNow()
send
or sendAsync
to completion. The behavior of actively running operations when interrupted is undefined. In particular, there is no guarantee that interrupted operations will terminate, or that code waiting on these operations will ever be notified.shutdown()
. Subclasses should override this method to implement the appropriate behavior.public void close()
send
or sendAsync
are run to completion, but no new request will be accepted. Running a request to completion may involve running several operations in the background, including waiting for responses to be delivered. This method waits until all operations have completed execution and the client has terminated. If interrupted while waiting, this method may attempt to stop all operations by calling shutdownNow()
. It then continues to wait until all actively executing operations have completed. The interrupt status will be re-asserted before this method returns.
If already terminated, invoking this method has no effect.
close
in interface AutoCloseable
shutdown()
and waits for tasks to complete execution with awaitTermination
.
© 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/java/net/http/HttpClient.html