New feature of jdk11: new HTTP API
New feature of jdk11: new HTTP API
brief introduction
Before jdk11, the HTTP function of java was very weak. It only provided httpurlconnection for HTTP connection, and it was very complex to use. Therefore, we generally use a third-party HTTP client (APACHE httpcomponents or okhttp) to make HTTP requests.
Everything changed completely in jdk11, in Java net. HTTP package, the latest httpclient, httprequest and httpresponse can fully meet your needs.
Basic process of using HTTP client request
Usually we need to make an HTTP request in the code, which usually has three steps.
Create HTTP client
To make an HTTP request, you need to establish a connection between an HTTP client and an HTTP server. The HTTP protocol is very complex and has many controllable parameters. Therefore, an httpclient is required for related configuration.
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
Creating httpclient is very simple. Just use newbuilder. We can specify version, connecttimeout, proxy, SSL, authentication or cookie.
Create HTTP request
Similarly, use httprequest Newbuilder () can be used to create HTTP requests.
HttpRequest getRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://www.flydean.com"))
.header("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/81.0.4044.122 Safari/537.36")
.build();
In the above example, we created a get request and set the URL and head of the request.
If it is a post request, you need to build a request body:
HttpRequest.BodyPublisher requestBody = HttpRequest.BodyPublishers
.ofString("{ 我是body }");
HttpRequest postRequest = HttpRequest.newBuilder()
.POST(requestBody)
.uri(URI.create("http://www.flydean.com"))
.build();
Send HTTP request
With client and request, we can send HTTP requests.
HttpResponse<String> response = client.send( getRequest,HttpResponse.BodyHandlers.ofString());
String respnseBody = response.body();
log.info(respnseBody);
Such a perfect HTTP request is completed.
Asynchronous HTTP request
In the above example, we use client Send to send an HTTP request, which is actually synchronous, which means that our program must wait until the request result is returned.
Httpclient also provides a method for asynchronous execution of sendasync. This method returns a completable future.
Let's take an example:
public void useAsyncHttp() {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();
CompletableFuture<Void> CompletableFuture=checkUri(client,URI.create("http://www.flydean.com"));
//获取CompletableFuture的值
CompletableFuture.join();
}
private CompletableFuture<Void> checkUri(HttpClient httpClient,URI uri){
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(uri)
.header("User-Agent",like Gecko) Chrome/81.0.4044.122 Safari/537.36")
.build();
return httpClient.sendAsync(request,HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::statusCode)
.thenApply(statusCode -> statusCode == 200 )
.exceptionally(ex -> false)
.thenAccept(valid ->
{
if (valid) {
log.info("uri {} is valid",uri);
} else {
log.info("uri {} is not valid",uri);
}
});
}
In the above example, we get the HTTP request, then call the thenApply and thenAccept of CompletableFuture to filter and process the results.
Completable future is a mixture of future and completionstage. We are all familiar with future. We can get the results of asynchronous execution through the get method. The completionstage represents an asynchronous computing stage. Different stages can depend on each other to form a cascade operation through the then * * * method. The operation of stream is a bit like that of promise then in ES6. Using completionstage can avoid callback hell. Completionstage can convert asynchronous callbacks into cascading operations.
For more information about completable future, you can refer to everything about completable future. Just read this article
The parameter of thenapply is a function, and thenaccept is a consumer.
Finally, we need to call completablefuture Join() to ensure that the asynchronous operation of completable future is completed.
Of course, call completabilefuture The get () method is also possible.