Professional Documents
Culture Documents
HTTP Cleint Api
HTTP Cleint Api
Need to send or receive data from a remote service over HTTP? The HTTP
new HttpClient and some new functionality it offers that wasn’t available
with HttpUrlConnection.
HttpClient Overview
The HTTP Client was added in JDK 11 after first being introduced as an
incubator feature in JDK 9. The goal of the HTTP Client was to replace
The HTTP Client addresses these shortcomings by offering support for the
Creating a Client
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.proxy(ProxySelector.of(...))
.authenticator(Authenticator.getDefault())
.build();
Copy
Creating a Request
.uri(URI.create("https://openjdk.org/"))
.timeout(Duration.ofSeconds(10))
.header("Content-Type",
"application/json")
.GET()
.build()
Copy
times.
##Sending Requests
Synchronous Requests
HttpResponse<String> response =
client.send(request,
BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
Copy
Asynchronous Requests
client.sendAsync(request,
BodyHandlers.ofString())
.thenApply(response ->
{ System.out.println
(response.statusCode());
return response;
} )
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
Copy
Reactive Streams
...
extends Flow.Publisher<ByteBuffer>
{ ... }
...
BodySubscriber<T>
apply(int statusCode,
HttpHeaders responseHeaders);
extends
Flow.Subscriber<List<ByteBuffer>>
{ ... }
Copy
Additional Reading