An HTTP Client.
An HttpClient
can be used to send requests and retrieve their responses. An HttpClient
is created through a builder
. The newBuilder
method returns a builder that creates instances of the default HttpClient
implementation. The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc. Once built, an HttpClient
is immutable, and can be used to send multiple requests.
An HttpClient
provides configuration information, and resource sharing, for all requests sent through it.
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
, 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.
Nested Classes
static interface
static enum
Defines the automatic redirection policy.
static enum
The HTTP protocol version.
Constructors
Returns an
Optional
containing the
Authenticator
set on this client.
Returns an Optional
containing the connect timeout duration for this client.
Returns an
Optional
containing this client's
Executor
.
Returns the follow redirects policy for this client.
Creates a new HttpClient
builder.
Returns a new HttpClient
with default settings.
Creates a new WebSocket
builder (optional operation).
Returns an Optional
containing the ProxySelector
supplied to this client.
Sends the given request using this client, blocking if necessary to get the response.
Sends the given request asynchronously using this client with the given response body handler.
Sends the given request asynchronously using this client with the given response body handler and push promise handler.
Returns this client's SSLContext
.
Returns the preferred HTTP protocol version for this client.
Methods declared in class java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
protected HttpClient()
Creates an HttpClient.
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.
Creates a new
HttpClient
builder.
Builders returned by this method create instances of the default HttpClient
implementation.
HttpClient.Builder
Returns an
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
Returns an
Optional
containing the
connect timeout durationfor this client. If the
connect timeout durationwas not set in the client's builder, then the
Optional
is empty.
Optional
containing this client's connect timeout duration
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 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.
Optional
containing the proxy selector supplied to this client.
Returns this client's
SSLContext
.
If no SSLContext
was set in this client's builder, then the default context is returned.
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.
SSLParameters
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.
Optional
containing this client's Authenticator
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.
Optional
containing this client's Executor
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.
T
- the response body type
request
- the request
responseBodyHandler
- the response body handler
IOException
- if an I/O error occurs when sending or receiving
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
.
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.
Equivalent to: sendAsync(request, responseBodyHandler, null)
.
T
- the response body type
request
- the request
responseBodyHandler
- the response body handler
CompletableFuture<HttpResponse<T>>
IllegalArgumentException
- if the request
argument is not a request that could have been validly built as specified by HttpRequest.Builder
.
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:
IOException
- if an I/O error occurs when sending or receivingSecurityException
- 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 type
request
- the request
responseBodyHandler
- the response body handler
pushPromiseHandler
- push promise handler, may be null
CompletableFuture<HttpResponse<T>>
IllegalArgumentException
- if the request
argument is not a request that could have been validly built as specified by HttpRequest.Builder
.
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);
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 support
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4