An HTTP Client.
An HttpClient
can be used to send requests and retrieve their responses. An HttpClient
is created through a builder
. 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.
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.3