Module Java - Part1
Module Java - Part1
http
Package java.net.http
Class HttpClient
java.lang.Object
java.net.http.HttpClient
extends Object
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.
● send(HttpRequest, BodyHandler) blocks until the request has been sent and the
Synchronous Example
.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();
System.out.println(response.statusCode());
System.out.println(response.body());
Asynchronous Example
.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);
Security checks
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.
Implementation Note:
If an explicit executor has not been set for an 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.
Since: