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, HTTP/2 or HTTP/3 ), 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:
HttpClient#send(HttpRequest, BodyHandler) blocks
until the request has been sent and the response has been received.HttpClient#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();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.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);
API Note
Resources allocated by the HttpClient may be
reclaimed early by closing the client.
Implementation Note
The BodyHandlers and BodySubscribers
classes provide some streaming
or publishing BodyHandler and BodySubscriber
implementations which allow to stream body data back to the caller.
In order for the resources associated with these streams to be
reclaimed, and for the HTTP request to be considered completed,
a caller must eventually obtain the streaming response body and close, cancel, or
read the returned streams to exhaustion. Likewise, a custom
BodySubscriber implementation should either request all data until onComplete or onError is signalled, or eventually
cancel its subscription.
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 streaming or publishing bodies to exhaustion
may stop delivery of data while leaving the request open, and
stall an
orderly shutdown. The shutdownNow() method, if called, will
attempt to cancel any such non-completed requests, but may cause
abrupt termination of any on going operation.
If not explicitly closed, the JDK
built-in implementation of the HttpClient releases
its resources when an HttpClient instance is no longer
strongly reachable, and all operations started on that instance have
eventually completed. This relies both on the garbage collector
to notice that the instance is no longer reachable, and on all
requests started on the client to eventually complete. Failure
to properly close streaming or publishing bodies
may prevent the associated requests from running to completion, and
prevent the resources allocated by the associated client from
being reclaimed by the garbage collector.
The default implementation of the HttpClient supports HTTP/1.1,
HTTP/2, and HTTP/3. Which version of the protocol is actually used when sending
a request can depend on multiple factors. In the case of HTTP/2, it may depend
on an initial upgrade to succeed (when using a plain connection), or on HTTP/2
being successfully negotiated during the Transport Layer Security (TLS) handshake.
If HTTP/2 is selected over a clear connection, and no HTTP/2 connection to the origin server already exists, the client will create a new connection and attempt an upgrade from HTTP/1.1 to HTTP/2. If the upgrade succeeds, then the response to this request will use HTTP/2. If the upgrade fails, then the response will be handled using HTTP/1.1.
Other constraints may also affect the selection of protocol version. For example, if HTTP/2 is requested through a proxy, and if the implementation does not support this mode, then HTTP/1.1 may be used.
The HTTP/3 protocol is not selected by default, but can be enabled by setting
the HttpClient preferred version or the
HttpRequest preferred version to
HTTP/3. Like for HTTP/2, which protocol version is
actually used when HTTP/3 is enabled may depend on several factors.
Configuration hints can
be provided
to help the HttpClient implementation decide how to establish
and carry out the HTTP exchange when the HTTP/3 protocol is enabled.
If no configuration hints are provided, the HttpClient will select
one as explained in the H3_DISCOVERY
option API documentation.
Note that a request whose URI scheme is not
"https" will never be sent over HTTP/3. In this implementation,
HTTP/3 is not used if a proxy is selected.
If a concrete instance of HttpClient doesn't support sending a
request through HTTP/3, an UnsupportedProtocolVersionException may be
thrown, either when building the client with
a preferred version set to HTTP/3,
or when attempting to send a request with HTTP/3 enabled when HTTP_3_URI_ONLY
was specified.
This may typically happen if the SSLContext
or SSLParameters configured on the client instance cannot
be used with HTTP/3.
UnsupportedProtocolVersionException, Builder#version(Version), HttpRequest.Builder#version(Version) , HttpRequest.Builder#setOption(HttpOption, Object) , HttpOption#H3_DISCOVERY
| Modifier and Type | Class and Description |
|---|---|
| public static interface | HttpClient.
A builder of HTTP Clients. |
| public static enum | HttpClient.
Defines the automatic redirection policy. |
| public static enum | HttpClient.
The HTTP protocol version. |
| Access | Constructor and Description |
|---|---|
| protected |
| Modifier and Type | Method and Description |
|---|---|
| public abstract Optional | Returns: anOptional containing this client's AuthenticatorReturns an |
| public boolean | Returns: true if this client terminated and
false if the timeout elapsed before terminationthe maximum time to wait duration)Blocks until all operations have completed execution after a shutdown
request, or the |
| public void | close()
Implements java. Initiates an orderly shutdown in which requests previously
submitted to |
| public abstract Optional | Returns: anOptional containing this client's connect timeout
durationReturns an |
| public abstract Optional | Returns: anOptional containing this client's CookieHandlerReturns an |
| public abstract Optional | |
| public abstract HttpClient. | Returns: this client's follow redirects settingReturns the follow redirects policy for this client. |
| public boolean | Returns: true if all tasks have completed following a shutdownReturns |
| public static HttpClient. | |
| public static HttpClient | |
| public WebSocket. | Returns: aWebSocket.BuilderCreates a new |
| public abstract Optional | Returns: anOptional containing the proxy selector supplied
to this client.Returns an |
| public abstract < the response body type T> HttpResponse | Returns: the responsethe request request, HttpResponse.the response body handler responseBodyHandlerSends the given request using this client, blocking if necessary to get the response. |
| public abstract < the response body type T> CompletableFuture | Returns: aCompletableFuture<HttpResponse<T>>the request request, HttpResponse.the response body handler responseBodyHandlerSends the given request asynchronously using this client with the given response body handler. |
| public abstract < the response body type T> CompletableFuture | Returns: aCompletableFuture<HttpResponse<T>>the request request, HttpResponse.the response body handler responseBodyHandler,push promise handler, may be null pushPromiseHandlerSends the given request asynchronously using this client with the given response body handler and push promise handler. |
| public void | shutdown()
Initiates an orderly shutdown in which requests previously
submitted with |
| public void | |
| public abstract SSLContext | |
| public abstract SSLParameters | |
| public abstract HttpClient. | Returns: the HTTP protocol version requestedReturns the preferred HTTP protocol version for this client. |
| HttpClient | back to summary |
|---|---|
| protected HttpClient() Creates an HttpClient. | |
| authenticator | back to summary |
|---|---|
| public abstract Optional Returns an
| |
| awaitTermination | back to summary |
|---|---|
| public boolean awaitTermination(Duration duration) throws InterruptedException Blocks until all operations have completed execution after a shutdown
request, or the 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. Implementation Specification The default implementation of this method checks for null arguments, but otherwise does nothing and returns true. Subclasses should override this method to implement the proper behavior.
| |
| close | back to summary |
|---|---|
| public void close() Implements java. Initiates an orderly shutdown in which requests previously
submitted to If interrupted while waiting, this method may attempt to stop all
operations by calling If already terminated, invoking this method has no effect. Implementation Specification The default implementation invokes
| |
| connectTimeout | back to summary |
|---|---|
| public abstract Optional Returns an | |
| cookieHandler | back to summary |
|---|---|
| public abstract Optional Returns an
| |
| executor | back to summary |
|---|---|
| public abstract Optional Returns an Even though this method may return an empty optional, the | |
| followRedirects | back to summary |
|---|---|
| public abstract HttpClient. Returns the follow redirects policy for this client. The default value
for client's built by builders that do not specify a redirect policy is
| |
| isTerminated | back to summary |
|---|---|
| public boolean isTerminated() Returns Note that Implementation Specification The default implementation of this method does nothing and returns false. Subclasses should override this method to implement the proper behavior.
| |
| newBuilder | back to summary |
|---|---|
| public static HttpClient. Creates a new Builders returned by this method create instances
of the default
| |
| newHttpClient | back to summary |
|---|---|
| public static HttpClient newHttpClient() Returns a new Equivalent to 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. Implementation Note The system-wide default values are retrieved at the time the
| |
| newWebSocketBuilder | back to summary |
|---|---|
| public WebSocket. Creates a new 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 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);
Implementation Specification The default implementation of this method throws
Implementation Note Both builder and When a
| |
| proxy | back to summary |
|---|---|
| public abstract Optional Returns an Even though this method may return an empty optional, the
| |
| send | back to summary |
|---|---|
| public abstract <T> HttpResponse Sends the given request using this client, blocking if necessary to get
the response. The returned If the operation is interrupted, the default
| |
| sendAsync | back to summary |
|---|---|
| public abstract <T> CompletableFuture Sends the given request asynchronously using this client with the given response body handler. Equivalent to:
| |
| sendAsync | back to summary |
|---|---|
| public abstract <T> CompletableFuture Sends the given request asynchronously using this client with the given response body handler and push promise handler. The returned completable future, if completed successfully, completes
with an Push promises received, if any, are
handled by the given The returned completable future completes exceptionally with:
The default
| |
| shutdown | back to summary |
|---|---|
| public void shutdown() Initiates an orderly shutdown in which requests previously
submitted with This method does not wait for previously submitted request
to complete execution. Use Implementation Specification The default implementation of this method does nothing. Subclasses should override this method to implement the appropriate behavior.
| |
| shutdownNow | back to summary |
|---|---|
| public void shutdownNow() This method attempts to initiate an immediate shutdown.
An implementation of this method may attempt to
interrupt operations that are actively running.
Operations are any tasks required to run a request previously
submitted with Implementation Specification The default implementation of this method simply calls
| |
| sslContext | back to summary |
|---|---|
| public abstract SSLContext sslContext() Returns this client's If no
| |
| sslParameters | back to summary |
|---|---|
| public abstract SSLParameters sslParameters() Returns a copy of this client's If no
| |
| version | back to summary |
|---|---|
| public abstract HttpClient. Returns the preferred HTTP protocol version for this client. The default
value is Implementation Note The protocol version that the
| |
Builders are created by invoking newBuilder. Each of the setter methods modifies the state of the builder
and returns the same instance. Builders are not thread-safe and should not be
used concurrently from multiple threads without external synchronization.
| Modifier and Type | Field and Description |
|---|---|
| public static final ProxySelector | NO_PROXY
A proxy selector that always return |
| Modifier and Type | Method and Description |
|---|---|
| public HttpClient. | Returns: this builderthe Authenticator authenticator)Sets an authenticator to use for HTTP authentication. |
| public HttpClient | Returns: a newHttpClientReturns a new |
| public HttpClient. | Returns: this builderthe duration to allow the underlying connection to be
established duration)Sets the connect timeout duration for this client. |
| public HttpClient. | Returns: this builderthe cookie handler cookieHandler)Sets a cookie handler. |
| public HttpClient. | |
| public HttpClient. | Returns: this builderthe redirection policy policySpecifies whether requests will automatically follow redirects issued by the server. |
| public default HttpClient. | Returns: this builderThe local address of the socket. Can be null. localAddr)Binds the socket to this local address when creating connections for sending requests. |
| public HttpClient. | Returns: this builderthe priority weighting priority)Sets the default priority for any HTTP/2 requests sent from this client. |
| public HttpClient. | Returns: this builderthe ProxySelector proxySelector)Sets a |
| public HttpClient. | |
| public HttpClient. | Returns: this builderthe SSLParameters sslParameters)Sets an |
| public HttpClient. | Returns: this builderthe requested HTTP protocol version versionSets the default preferred HTTP protocol version for requests issued by this client. |
| NO_PROXY | back to summary |
|---|---|
| public static final ProxySelector NO_PROXY A proxy selector that always return This is a convenience object that can be passed to
| |
| authenticator | back to summary |
|---|---|
| public HttpClient. Sets an authenticator to use for HTTP authentication. Implementation Note In the JDK built-in implementation of the
| |
| build | back to summary |
|---|---|
| public HttpClient build() Returns a new
| |
| connectTimeout | back to summary |
|---|---|
| public HttpClient. Sets the connect timeout duration for this client. In the case where a new connection needs to be established, if
the connection cannot be established within the given Implementation Specification A connection timeout applies to the entire connection phase, from the moment a connection is requested until it is established. Implementations are recommended to ensure that the connection timeout covers any SSL/TLS handshakes. Implementation Note The built-in JDK implementation of the connection timeout covers any SSL/TLS handshakes.
| |
| cookieHandler | back to summary |
|---|---|
| public HttpClient. Sets a cookie handler.
| |
| executor | back to summary |
|---|---|
| public HttpClient. Sets the executor to be used for asynchronous and dependent tasks. If this method is not invoked prior to building, a default executor is created for each newly built Implementation Note The default executor uses a thread pool, with a custom thread factory.
| |
| followRedirects | back to summary |
|---|---|
| public HttpClient. Specifies whether requests will automatically follow redirects issued by the server. If this method is not invoked prior to building, then newly built clients will use a default redirection
policy of
| |
| localAddress | back to summary |
|---|---|
| public default HttpClient. Binds the socket to this local address when creating connections for sending requests. If no local address is set or Common usages of the Implementation Specification The default implementation of this method throws
| |
| priority | back to summary |
|---|---|
| public HttpClient. Sets the default priority for any HTTP/2 requests sent from this
client. The value provided must be between
| |
| proxy | back to summary |
|---|---|
| public HttpClient. Sets a API Note
Implementation Note If this method is not invoked prior to building,
then newly built clients will use the default proxy selector, which is usually
adequate for client applications. The default proxy selector supports
a set of system properties related to
proxy settings. This default behavior can be disabled by
supplying an explicit proxy selector, such as
| |
| sslContext | back to summary |
|---|---|
| public HttpClient. Sets an If this method is not invoked prior to building, then newly built clients will use the default context, which is normally adequate for client applications that do not need to specify protocols, or require client authentication.
| |
| sslParameters | back to summary |
|---|---|
| public HttpClient. Sets an If this method is not invoked prior to building, then newly built clients will use a default, implementation specific, set of parameters. Some parameters which are used internally by the HTTP Client implementation (such as the application protocol list) should not be set by callers, as they may be ignored. The contents of the given object are copied.
| |
| version | back to summary |
|---|---|
| public HttpClient. Sets the default preferred HTTP protocol version for requests issued by this client. If this method is not invoked prior to building, then newly built clients will prefer HTTP/2. If a request doesn't have a preferred version, then the effective preferred version for the request is the client's preferred version. Implementation Note Some constraints may also affect the selection of the actual protocol version.
| |
The automatic redirection policy is checked whenever a 3XX
response code is received. If redirection does not happen automatically,
then the response, containing the 3XX response code, is returned,
where it can be handled manually.
Redirect policy is set through the Builder.followRedirects
method.
Implementation Note
When automatic redirection occurs, the request method of the
redirected request may be modified depending on the specific 30X
status code, as specified in
RFC 7231. In addition, the 301 and 302 status codes
cause a POST request to be converted to a GET in the
redirected request.
| Modifier and Type | Field and Description |
|---|---|
| public static final HttpClient. | ALWAYS
Always redirect. |
| public static final HttpClient. | NEVER
Never redirect. |
| public static final HttpClient. | NORMAL
Always redirect, except from HTTPS URLs to HTTP URLs. |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public static HttpClient. | |
| public static HttpClient. |
| ALWAYS | back to summary |
|---|---|
| public static final HttpClient. Always redirect. | |
| NEVER | back to summary |
|---|---|
| public static final HttpClient. Never redirect. | |
| NORMAL | back to summary |
|---|---|
| public static final HttpClient. Always redirect, except from HTTPS URLs to HTTP URLs. | |
| Redirect | back to summary |
|---|---|
| private Redirect() | |
| valueOf | back to summary |
|---|---|
| public static HttpClient. | |
| values | back to summary |
|---|---|
| public static HttpClient. | |
| Modifier and Type | Field and Description |
|---|---|
| public static final HttpClient. | HTTP_1_1
HTTP version 1.1 |
| public static final HttpClient. | HTTP_2
HTTP version 2 |
| public static final HttpClient. | HTTP_3
HTTP version 3 |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public static HttpClient. | |
| public static HttpClient. |
| HTTP_1_1 | back to summary |
|---|---|
| public static final HttpClient. HTTP version 1.1 | |
| HTTP_2 | back to summary |
|---|---|
| public static final HttpClient. HTTP version 2 | |
| HTTP_3 | back to summary |
|---|---|
| public static final HttpClient. HTTP version 3
| |
| Version | back to summary |
|---|---|
| private Version() | |
| valueOf | back to summary |
|---|---|
| public static HttpClient. | |
| values | back to summary |
|---|---|
| public static HttpClient. | |