APIdia Launch Partner
Top Description Inners Constructors Methods
java.net.http

public abstract Class HttpClient

extends Object
implements AutoCloseable
Class Inheritance
All Implemented Interfaces
java.lang.AutoCloseable
Known Direct Subclasses
jdk.internal.net.http.HttpClientFacade, jdk.internal.net.http.HttpClientImpl
Imports
java.io.IOException, .UncheckedIOException, java.net.InetAddress, .URI, .Authenticator, .CookieHandler, .InetSocketAddress, .Proxy, .ProxySelector, java.net.http.HttpOption.Http3DiscoveryMode, .HttpResponse.BodyHandlers, .HttpResponse.BodySubscriber, .HttpResponse.BodySubscribers, .HttpResponse.BodyHandler, .HttpResponse.PushPromiseHandler, java.nio.channels.Selector, java.time.Duration, java.util.Objects, .Optional, java.util.concurrent.CompletableFuture, .Executor, .Flow.Subscription, javax.net.ssl.SSLContext, .SSLParameters, jdk.internal.net.http.HttpClientBuilderImpl

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, 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:

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());
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);
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.

Since
11
See Also
UnsupportedProtocolVersionException, Builder#version(Version), HttpRequest.Builder#version(Version), HttpRequest.Builder#setOption(HttpOption, Object), HttpOption#H3_DISCOVERY

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
public static enum
HttpClient.Redirect

Defines the automatic redirection policy.

public static enum
HttpClient.Version

The HTTP protocol version.

Constructor Summary

AccessConstructor and Description
protected
HttpClient()

Creates an HttpClient.

Method Summary

Modifier and TypeMethod and Description
public abstract Optional<Authenticator>

Returns:

an Optional containing this client's Authenticator
authenticator
()

Returns an Optional containing the Authenticator set on this client.

public boolean

Returns:

true if this client terminated and false if the timeout elapsed before termination
awaitTermination
(Duration
the maximum time to wait
duration
)

Blocks until all operations have completed execution after a shutdown request, or the duration elapses, or the current thread is interrupted, whichever happens first.

public void
close()

Implements java.lang.AutoCloseable.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.

public abstract Optional<Duration>

Returns:

an Optional containing this client's connect timeout duration
connectTimeout
()

Returns an Optional containing the connect timeout duration for this client.

public abstract Optional<CookieHandler>

Returns:

an Optional containing this client's CookieHandler
cookieHandler
()

Returns an Optional containing this client's CookieHandler.

public abstract Optional<Executor>

Returns:

an Optional containing this client's Executor
executor
()

Returns an Optional containing this client's Executor.

public abstract HttpClient.Redirect

Returns:

this client's follow redirects setting
followRedirects
()

Returns the follow redirects policy for this client.

public boolean

Returns:

true if all tasks have completed following a shutdown
isTerminated
()

Returns true if all operations have completed following a shutdown.

public static HttpClient.Builder

Returns:

an HttpClient.Builder
newBuilder
()

Creates a new HttpClient builder.

public static HttpClient

Returns:

a new HttpClient
newHttpClient
()

Returns a new HttpClient with default settings.

public WebSocket.Builder

Returns:

a WebSocket.Builder
newWebSocketBuilder
()

Creates a new WebSocket builder (optional operation).

public abstract Optional<ProxySelector>

Returns:

an Optional containing the proxy selector supplied to this client.
proxy
()

Returns an Optional containing the ProxySelector supplied to this client.

public abstract <
the response body type
T
>
HttpResponse<T>

Returns:

the response
send
(HttpRequest
the request
request
,
HttpResponse.BodyHandler<T>
the response body handler
responseBodyHandler
)

Sends the given request using this client, blocking if necessary to get the response.

public abstract <
the response body type
T
>
CompletableFuture<HttpResponse<T>>

Returns:

a CompletableFuture<HttpResponse<T>>
sendAsync
(HttpRequest
the request
request
,
HttpResponse.BodyHandler<T>
the response body handler
responseBodyHandler
)

Sends the given request asynchronously using this client with the given response body handler.

public abstract <
the response body type
T
>
CompletableFuture<HttpResponse<T>>

Returns:

a CompletableFuture<HttpResponse<T>>
sendAsync
(HttpRequest
the request
request
,
HttpResponse.BodyHandler<T>
the response body handler
responseBodyHandler
,
HttpResponse.PushPromiseHandler<T>
push promise handler, may be null
pushPromiseHandler
)

Sends 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 send or sendAsync are run to completion, but no new request will be accepted.

public void
shutdownNow()

This method attempts to initiate an immediate shutdown.

public abstract SSLContext

Returns:

this client's SSLContext
sslContext
()

Returns this client's SSLContext.

public abstract SSLParameters

Returns:

this client's SSLParameters
sslParameters
()

Returns a copy of this client's SSLParameters.

public abstract HttpClient.Version

Returns:

the HTTP protocol version requested
version
()

Returns the preferred HTTP protocol version for this client.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

HttpClientback to summary
protected HttpClient()

Creates an HttpClient.

Method Detail

authenticatorback to summary
public abstract Optional<Authenticator> authenticator()

Returns an Optional containing the Authenticator set on this client. If no Authenticator was set in the client's builder, then the Optional is empty.

Returns:Optional<Authenticator>

an Optional containing this client's Authenticator

awaitTerminationback to summary
public boolean awaitTermination(Duration duration) throws InterruptedException

Blocks until all operations have completed execution after a shutdown request, or the 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.

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.

Parameters
duration:Duration

the maximum time to wait

Returns:boolean

true if this client terminated and false if the timeout elapsed before termination

Exceptions
InterruptedException:
if interrupted while waiting
Since
21
See Also
Implementation Note on closing the HttpClient
closeback to summary
public void close()

Implements java.lang.AutoCloseable.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. 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 interrupted status will be re-asserted before this method returns.

If already terminated, invoking this method has no effect.

Implementation Specification

The default implementation invokes shutdown() and waits for tasks to complete execution with awaitTermination.

Annotations
@Override
Since
21
See Also
Implementation Note on closing the HttpClient
connectTimeoutback to summary
public abstract Optional<Duration> connectTimeout()

Returns an 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.

Returns:Optional<Duration>

an Optional containing this client's connect timeout duration

cookieHandlerback to summary
public abstract Optional<CookieHandler> cookieHandler()

Returns an Optional containing this client's CookieHandler. If no CookieHandler was set in this client's builder, then the Optional is empty.

Returns:Optional<CookieHandler>

an Optional containing this client's CookieHandler

executorback to summary
public abstract Optional<Executor> executor()

Returns an 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.

Returns:Optional<Executor>

an Optional containing this client's Executor

followRedirectsback to summary
public abstract HttpClient.Redirect followRedirects()

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 NEVER.

Returns:HttpClient.Redirect

this client's follow redirects setting

isTerminatedback to summary
public boolean isTerminated()

Returns 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.

Implementation Specification

The default implementation of this method does nothing and returns false. Subclasses should override this method to implement the proper behavior.

Returns:boolean

true if all tasks have completed following a shutdown

Since
21
See Also
Implementation Note on closing the HttpClient
newBuilderback to summary
public static HttpClient.Builder newBuilder()

Creates a new HttpClient builder.

Builders returned by this method create instances of the default HttpClient implementation.

Returns:HttpClient.Builder

an HttpClient.Builder

newHttpClientback to summary
public static HttpClient newHttpClient()

Returns a new 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.

Implementation Note

The system-wide default values are retrieved at the time the 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.

Returns:HttpClient

a new HttpClient

Exceptions
UncheckedIOException:
if necessary underlying IO resources required to build a new HttpClient cannot be allocated.
newWebSocketBuilderback to summary
public WebSocket.Builder newWebSocketBuilder()

Creates a new WebSocket builder (optional operation).

Example

HttpClient client = HttpClient.newHttpClient(); CompletableFuture<WebSocket> ws = client.newWebSocketBuilder() .buildAsync(URI.create("ws://websocket.example.com"), listener);
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);
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 UnsupportedOperationException. Clients obtained through HttpClient#newHttpClient() or HttpClient#newBuilder() return a WebSocket builder.

Implementation Note

Both builder and WebSockets 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.

Returns:WebSocket.Builder

a WebSocket.Builder

Exceptions
UnsupportedOperationException:
if this HttpClient does not provide WebSocket support
proxyback to summary
public abstract Optional<ProxySelector> proxy()

Returns an 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.

Returns:Optional<ProxySelector>

an Optional containing the proxy selector supplied to this client.

sendback to summary
public abstract <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) throws IOException, InterruptedException

Sends the given request using this client, blocking if necessary to get the response. The returned 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.

  • With HTTP/1.1, an attempt to cancel may cause the underlying connection to be closed abruptly.
  • With HTTP/2, an attempt to cancel may cause the stream to be reset, or in certain circumstances, may also cause the connection to be closed abruptly, if, for instance, the thread is currently trying to write to the underlying socket.
Parameters
<T>
the response body type
request:HttpRequest

the request

responseBodyHandler:HttpResponse.BodyHandler<T>

the response body handler

Returns:HttpResponse<T>

the response

Exceptions
IOException:
if an I/O error occurs when sending or receiving, or the client has shut down
InterruptedException:
if the operation is interrupted
IllegalArgumentException:
if the request argument is not a request that could have been validly built as specified by HttpRequest.Builder.
sendAsyncback to summary
public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)

Sends the given request asynchronously using this client with the given response body handler.

Equivalent to: sendAsync(request, responseBodyHandler, null).

Parameters
<T>
the response body type
request:HttpRequest

the request

responseBodyHandler:HttpResponse.BodyHandler<T>

the response body handler

Returns:CompletableFuture<HttpResponse<T>>

a CompletableFuture<HttpResponse<T>>

Exceptions
IllegalArgumentException:
if the request argument is not a request that could have been validly built as specified by HttpRequest.Builder.
sendAsyncback to summary
public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler, HttpResponse.PushPromiseHandler<T> pushPromiseHandler)

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 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:

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.

  • With HTTP/1.1, an attempt to cancel may cause the underlying connection to be closed abruptly.
  • With HTTP/2, an attempt to cancel may cause the stream to be reset.
Parameters
<T>
the response body type
request:HttpRequest

the request

responseBodyHandler:HttpResponse.BodyHandler<T>

the response body handler

pushPromiseHandler:HttpResponse.PushPromiseHandler<T>

push promise handler, may be null

Returns:CompletableFuture<HttpResponse<T>>

a CompletableFuture<HttpResponse<T>>

Exceptions
IllegalArgumentException:
if the request argument is not a request that could have been validly built as specified by HttpRequest.Builder.
shutdownback to summary
public 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. 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.

Implementation Specification

The default implementation of this method does nothing. Subclasses should override this method to implement the appropriate behavior.

Since
21
See Also
Implementation Note on closing the HttpClient
shutdownNowback 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 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.

Implementation Specification

The default implementation of this method simply calls shutdown(). Subclasses should override this method to implement the appropriate behavior.

Since
21
See Also
Implementation Note on closing the HttpClient
sslContextback to summary
public abstract SSLContext sslContext()

Returns this client's SSLContext.

If no SSLContext was set in this client's builder, then the default context is returned.

Returns:SSLContext

this client's SSLContext

sslParametersback to summary
public abstract SSLParameters sslParameters()

Returns a copy of this client's 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.

Returns:SSLParameters

this client's SSLParameters

versionback to summary
public abstract HttpClient.Version version()

Returns the preferred HTTP protocol version for this client. The default value is HttpClient.Version#HTTP_2

Implementation Note

The protocol version that the HttpClient eventually decides to use for a request is affected by various factors noted in protocol version selection section.

Returns:HttpClient.Version

the HTTP protocol version requested

java.net.http back to summary

public Interface HttpClient.Builder

Known Direct Implementers
jdk.internal.net.http.HttpClientBuilderImpl

A builder of HTTP Clients.

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.

Since
11

Field Summary

Modifier and TypeField and Description
public static final ProxySelector
NO_PROXY

A proxy selector that always return Proxy#NO_PROXY implying a direct connection.

Method Summary

Modifier and TypeMethod and Description
public HttpClient.Builder

Returns:

this builder
authenticator
(Authenticator
the Authenticator
authenticator
)

Sets an authenticator to use for HTTP authentication.

public HttpClient

Returns:

a new HttpClient
build
()

Returns a new HttpClient built from the current state of this builder.

public HttpClient.Builder

Returns:

this builder
connectTimeout
(Duration
the duration to allow the underlying connection to be established
duration
)

Sets the connect timeout duration for this client.

public HttpClient.Builder

Returns:

this builder
cookieHandler
(CookieHandler
the cookie handler
cookieHandler
)

Sets a cookie handler.

public HttpClient.Builder

Returns:

this builder
executor
(Executor
the Executor
executor
)

Sets the executor to be used for asynchronous and dependent tasks.

public HttpClient.Builder

Returns:

this builder
followRedirects
(HttpClient.Redirect
the redirection policy
policy
)

Specifies whether requests will automatically follow redirects issued by the server.

public default HttpClient.Builder

Returns:

this builder
localAddress
(InetAddress
The local address of the socket. Can be null.
localAddr
)

Binds the socket to this local address when creating connections for sending requests.

public HttpClient.Builder

Returns:

this builder
priority
(int
the priority weighting
priority
)

Sets the default priority for any HTTP/2 requests sent from this client.

public HttpClient.Builder

Returns:

this builder
proxy
(ProxySelector
the ProxySelector
proxySelector
)

Sets a java.net.ProxySelector.

public HttpClient.Builder

Returns:

this builder
sslContext
(SSLContext
the SSLContext
sslContext
)

Sets an SSLContext.

public HttpClient.Builder

Returns:

this builder
sslParameters
(SSLParameters
the SSLParameters
sslParameters
)

Sets an SSLParameters.

public HttpClient.Builder

Returns:

this builder
version
(HttpClient.Version
the requested HTTP protocol version
version
)

Sets the default preferred HTTP protocol version for requests issued by this client.

Field Detail

NO_PROXYback to summary
public static final ProxySelector NO_PROXY

A proxy selector that always return Proxy#NO_PROXY implying a direct connection.

This is a convenience object that can be passed to proxy(ProxySelector) in order to build an instance of HttpClient that uses no proxy.

Method Detail

authenticatorback to summary
public HttpClient.Builder authenticator(Authenticator authenticator)

Sets an authenticator to use for HTTP authentication.

Implementation Note

In the JDK built-in implementation of the HttpClient, if a HttpRequest has an Authorization or Proxy-Authorization header set then its value is used and the Authenticator is not invoked for the corresponding authentication. In this case, any authentication errors are returned to the user and requests are not automatically retried. Additionally, the JDK built-in implementation currently only supports HTTP Basic authentication.

Parameters
authenticator:Authenticator

the Authenticator

Returns:HttpClient.Builder

this builder

buildback to summary
public HttpClient build()

Returns a new HttpClient built from the current state of this builder.

Returns:HttpClient

a new HttpClient

Exceptions
UncheckedIOException:
may be thrown if underlying IO resources required by the implementation cannot be allocated, or if the resulting configuration does not satisfy the implementation requirements. For instance, if the implementation requires a Selector, and opening one fails due to lack of necessary resources, or if the preferred protocol version is not supported by the implementation or cannot be used in this configuration.
connectTimeoutback to summary
public HttpClient.Builder connectTimeout(Duration duration)

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 duration, then HttpClient::send throws an HttpConnectTimeoutException, or HttpClient::sendAsync completes exceptionally with an HttpConnectTimeoutException. If a new connection does not need to be established, for example if a connection can be reused from a previous request, then this timeout duration has no effect.

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.

Parameters
duration:Duration

the duration to allow the underlying connection to be established

Returns:HttpClient.Builder

this builder

Exceptions
IllegalArgumentException:
if the duration is non-positive
See Also
Configuring timeout for request execution
cookieHandlerback to summary
public HttpClient.Builder cookieHandler(CookieHandler cookieHandler)

Sets a cookie handler.

Parameters
cookieHandler:CookieHandler

the cookie handler

Returns:HttpClient.Builder

this builder

executorback to summary
public HttpClient.Builder executor(Executor executor)

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 HttpClient.

Implementation Note

The default executor uses a thread pool, with a custom thread factory.

Parameters
executor:Executor

the Executor

Returns:HttpClient.Builder

this builder

followRedirectsback to summary
public HttpClient.Builder followRedirects(HttpClient.Redirect policy)

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 NEVER.

Parameters
policy:HttpClient.Redirect

the redirection policy

Returns:HttpClient.Builder

this builder

localAddressback to summary
public default HttpClient.Builder localAddress(InetAddress localAddr)

Binds the socket to this local address when creating connections for sending requests.

If no local address is set or null is passed to this method then sockets created by the HTTP client will be bound to an automatically assigned socket address.

Common usages of the HttpClient do not require this method to be called. Setting a local address, through this method, is only for advanced usages where users of the HttpClient require specific control on which network interface gets used for the HTTP communication. Callers of this method are expected to be aware of the networking configurations of the system where the HttpClient will be used and care should be taken to ensure the correct localAddr is passed. Failure to do so can result in requests sent through the HttpClient to fail.

Implementation Specification

The default implementation of this method throws UnsupportedOperationException. Builders obtained through HttpClient#newBuilder() provide an implementation of this method that allows setting the local address.

Parameters
localAddr:InetAddress

The local address of the socket. Can be null.

Returns:HttpClient.Builder

this builder

Exceptions
UnsupportedOperationException:
if this builder doesn't support configuring a local address or if the passed localAddr is not supported by this HttpClient implementation.
Since
19
priorityback to summary
public HttpClient.Builder priority(int priority)

Sets the default priority for any HTTP/2 requests sent from this client. The value provided must be between 1 and 256 (inclusive).

Parameters
priority:int

the priority weighting

Returns:HttpClient.Builder

this builder

Exceptions
IllegalArgumentException:
if the given priority is out of range
proxyback to summary
public HttpClient.Builder proxy(ProxySelector proxySelector)

Sets a java.net.ProxySelector.

API Note

ProxySelector::of provides a ProxySelector which uses a single proxy for all requests. The system-wide proxy selector can be retrieved by ProxySelector#getDefault().

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 NO_PROXY or one returned by ProxySelector::of, before building.

Parameters
proxySelector:ProxySelector

the ProxySelector

Returns:HttpClient.Builder

this builder

sslContextback to summary
public HttpClient.Builder sslContext(SSLContext sslContext)

Sets an SSLContext.

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.

Parameters
sslContext:SSLContext

the SSLContext

Returns:HttpClient.Builder

this builder

sslParametersback to summary
public HttpClient.Builder sslParameters(SSLParameters sslParameters)

Sets an SSLParameters.

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.

Parameters
sslParameters:SSLParameters

the SSLParameters

Returns:HttpClient.Builder

this builder

versionback to summary
public HttpClient.Builder version(HttpClient.Version version)

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.

Parameters
version:HttpClient.Version

the requested HTTP protocol version

Returns:HttpClient.Builder

this builder

java.net.http back to summary

public final Enum HttpClient.Redirect

extends Enum<HttpClient.Redirect>
Class Inheritance

Defines the automatic redirection policy.

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.

Since
11

Field Summary

Modifier and TypeField and Description
public static final HttpClient.Redirect
ALWAYS

Always redirect.

public static final HttpClient.Redirect
NEVER

Never redirect.

public static final HttpClient.Redirect
NORMAL

Always redirect, except from HTTPS URLs to HTTP URLs.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static HttpClient.Redirect
public static HttpClient.Redirect[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

ALWAYSback to summary
public static final HttpClient.Redirect ALWAYS

Always redirect.

NEVERback to summary
public static final HttpClient.Redirect NEVER

Never redirect.

NORMALback to summary
public static final HttpClient.Redirect NORMAL

Always redirect, except from HTTPS URLs to HTTP URLs.

Constructor Detail

Redirectback to summary
private Redirect()

Method Detail

valueOfback to summary
public static HttpClient.Redirect valueOf(String name)
valuesback to summary
public static HttpClient.Redirect[] values()
java.net.http back to summary

public final Enum HttpClient.Version

extends Enum<HttpClient.Version>
Class Inheritance

The HTTP protocol version.
Since
11

Field Summary

Modifier and TypeField and Description
public static final HttpClient.Version
HTTP_1_1

HTTP version 1.1

public static final HttpClient.Version
HTTP_2

HTTP version 2

public static final HttpClient.Version
HTTP_3

HTTP version 3

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static HttpClient.Version
public static HttpClient.Version[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

HTTP_1_1back to summary
public static final HttpClient.Version HTTP_1_1

HTTP version 1.1

HTTP_2back to summary
public static final HttpClient.Version HTTP_2

HTTP version 2

HTTP_3back to summary
public static final HttpClient.Version HTTP_3

HTTP version 3

Since
26

Constructor Detail

Versionback to summary
private Version()

Method Detail

valueOfback to summary
public static HttpClient.Version valueOf(String name)
valuesback to summary
public static HttpClient.Version[] values()