- java.lang.Object
-
- java.net.http.HttpClient
-
public abstract class HttpClient extends Object
An HTTP Client.An
HttpClientcan be used to send requests and retrieve their responses. AnHttpClientis created through abuilder. 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, anHttpClientis immutable, and can be used to send multiple requests.An
HttpClientprovides configuration information, and resource sharing, for all requests sent through it.A
BodyHandlermust be supplied for eachHttpRequestsent. TheBodyHandlerdetermines how to handle the response body, if any. Once anHttpResponseis 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. ThesendAsyncmethod returns immediately with aCompletableFuture<HttpResponse>. TheCompletableFuturecompletes when the response becomes available. The returnedCompletableFuturecan 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
URLPermissionis required to access the destination server, and proxy server if one has been configured. The form of theURLPermissionrequired to access a proxy has amethodparameter of"CONNECT"(for all kinds of proxying) and aURLstring of the form"socket://host:port"where host and port specify the proxy's address.- Since:
- 11
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceHttpClient.BuilderA builder of HTTP Clients.static classHttpClient.RedirectDefines the automatic redirection policy.static classHttpClient.VersionThe HTTP protocol version.
-
Constructor Summary
Constructors Modifier Constructor Description protectedHttpClient()Creates an HttpClient.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description abstract Optional<Authenticator>authenticator()Returns anOptionalcontaining theAuthenticatorset on this client.abstract Optional<Duration>connectTimeout()Returns anOptionalcontaining the connect timeout duration for this client.abstract Optional<CookieHandler>cookieHandler()Returns anOptionalcontaining this client'sCookieHandler.abstract Optional<Executor>executor()Returns anOptionalcontaining this client'sExecutor.abstract HttpClient.RedirectfollowRedirects()Returns the follow redirects policy for this client.static HttpClient.BuildernewBuilder()Creates a newHttpClientbuilder.static HttpClientnewHttpClient()Returns a newHttpClientwith default settings.WebSocket.BuildernewWebSocketBuilder()Creates a newWebSocketbuilder (optional operation).abstract Optional<ProxySelector>proxy()Returns anOptionalcontaining theProxySelectorsupplied to this client.abstract <T> HttpResponse<T>send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)Sends the given request using this client, blocking if necessary to get the response.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.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.abstract SSLContextsslContext()Returns this client'sSSLContext.abstract SSLParameterssslParameters()Returns a copy of this client'sSSLParameters.abstract HttpClient.Versionversion()Returns the preferred HTTP protocol version for this client.
-
-
-
Method Detail
-
newHttpClient
public static HttpClient newHttpClient()
Returns a newHttpClientwith 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.
- Returns:
- a new HttpClient
-
newBuilder
public static HttpClient.Builder newBuilder()
Creates a newHttpClientbuilder.- Returns:
- an
HttpClient.Builder
-
cookieHandler
public abstract Optional<CookieHandler> cookieHandler()
Returns anOptionalcontaining this client'sCookieHandler. If noCookieHandlerwas set in this client's builder, then theOptionalis empty.- Returns:
- an
Optionalcontaining this client'sCookieHandler
-
connectTimeout
public abstract Optional<Duration> connectTimeout()
Returns anOptionalcontaining the connect timeout duration for this client. If the connect timeout duration was not set in the client's builder, then theOptionalis empty.- Returns:
- an
Optionalcontaining this client's connect timeout duration
-
followRedirects
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 isNEVER.- Returns:
- this client's follow redirects setting
-
proxy
public abstract Optional<ProxySelector> proxy()
Returns anOptionalcontaining theProxySelectorsupplied to this client. If no proxy selector was set in this client's builder, then theOptionalis empty.Even though this method may return an empty optional, the
HttpClientmay still have a non-exposed default proxy selector that is used for sending HTTP requests.- Returns:
- an
Optionalcontaining the proxy selector supplied to this client.
-
sslContext
public abstract SSLContext sslContext()
Returns this client'sSSLContext.If no
SSLContextwas set in this client's builder, then the default context is returned.- Returns:
- this client's SSLContext
-
sslParameters
public abstract SSLParameters sslParameters()
Returns a copy of this client'sSSLParameters.If no
SSLParameterswere set in the client's builder, then an implementation specific default set of parameters, that the client will use, is returned.- Returns:
- this client's
SSLParameters
-
authenticator
public abstract Optional<Authenticator> authenticator()
Returns anOptionalcontaining theAuthenticatorset on this client. If noAuthenticatorwas set in the client's builder, then theOptionalis empty.- Returns:
- an
Optionalcontaining this client'sAuthenticator
-
version
public abstract HttpClient.Version version()
Returns the preferred HTTP protocol version for this client. The default value isHttpClient.Version.HTTP_2- Returns:
- the HTTP protocol version requested
-
executor
public abstract Optional<Executor> executor()
Returns anOptionalcontaining this client'sExecutor. If noExecutorwas set in the client's builder, then theOptionalis empty.Even though this method may return an empty optional, the
HttpClientmay still have an non-exposed default executor that is used for executing asynchronous and dependent tasks.- Returns:
- an
Optionalcontaining this client'sExecutor
-
send
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 returnedHttpResponse<T>contains the response status, headers, and body ( as handled by given response body handler ).- Type Parameters:
T- the response body type- Parameters:
request- the requestresponseBodyHandler- the response body handler- Returns:
- the response
- Throws:
IOException- if an I/O error occurs when sending or receivingInterruptedException- if the operation is interruptedIllegalArgumentException- if therequestargument is not a request that could have been validly built as specified byHttpRequest.Builder.SecurityException- If a security manager has been installed and it deniesaccessto the URL in the given request, or proxy if one is configured. See security checks for further information.
-
sendAsync
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).- Type Parameters:
T- the response body type- Parameters:
request- the requestresponseBodyHandler- the response body handler- Returns:
- a
CompletableFuture<HttpResponse<T>> - Throws:
IllegalArgumentException- if therequestargument is not a request that could have been validly built as specified byHttpRequest.Builder.
-
sendAsync
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. AnullvaluedpushPromiseHandlerrejects any push promises.The returned completable future completes exceptionally with:
IOException- if an I/O error occurs when sending or receivingSecurityException- If a security manager has been installed and it deniesaccessto the URL in the given request, or proxy if one is configured. See security checks for further information.
- Type Parameters:
T- the response body type- Parameters:
request- the requestresponseBodyHandler- the response body handlerpushPromiseHandler- push promise handler, may be null- Returns:
- a
CompletableFuture<HttpResponse<T>> - Throws:
IllegalArgumentException- if therequestargument is not a request that could have been validly built as specified byHttpRequest.Builder.
-
newWebSocketBuilder
public WebSocket.Builder newWebSocketBuilder()
Creates a newWebSocketbuilder (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);- Returns:
- a
WebSocket.Builder - Throws:
UnsupportedOperationException- if thisHttpClientdoes not provide WebSocket support
-
-