brief introduction
Before JDK11, the HTTP function of java was very weak, only HttpURLConnection was provided for HTTP connection, and it was very complex to use. So we usually use the third-party HTTP client (Apache HttpComponents or OkHttp) to make HTTP requests.
Everything has changed in JDK11. In the java.net.http package, the latest HttpClient, HttpRequest and HttpResponse can fully meet your needs.
More at www.flydean.com
Basic process of using HTTP Client request
Usually we need to make an HTTP request in the code, which usually has three steps.
- Build an HTTP client.
- Generate an HTTP Request.
- Use HTTP Client to send HTTP Request to get an HTTP Response.
Create HTTP Client
To make an HTTP request, you need to establish a connection between the HTTP client and the HTTP server. The HTTP protocol is very complex and has many controllable parameters. Therefore, an HttpClient is needed for configuration.
HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(5)) .followRedirects(HttpClient.Redirect.ALWAYS) .build();
It's easy to create HttpClient, just use newBuilder. We can specify version,connectTimeout,proxy,SSL, authentication or cookie, etc.
Create HTTP Request
Similarly, 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("{ I am 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);
This completes a perfect HTTP request.
Asynchronous HTTP request
In the above example, we use client.send to send http request, which is actually synchronous, which means 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 another 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")); //Get the value of completabilefuture completableFuture.join(); } private CompletableFuture<Void> checkUri(HttpClient httpClient, URI uri){ HttpRequest request = HttpRequest.newBuilder() .GET() .uri(uri) .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(); 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. Everyone is familiar with Future. You can get asynchronous execution results through get method. The CompletionStage represents a stage of asynchronous computing. Different stages can depend on each other to form a cascade operation through the then * * method. Similar to the Stream operation, like promise then in ES6, using CompletionStage can avoid callback to hell. CompletionStage can convert asynchronous callbacks into cascading operations.
For more information on completable future, please refer to All about completable future, this article is enough
The parameter of thenApply is a Function, and thenAccept is a Consumer.
Finally, we need to call completabilefuture. Join() to ensure that the asynchronous operation of completabilefuture is completed.
Of course, it is also possible to call the completabilefuture. Get() method.
summary
This article explains the newly created HTTP Client operation of JDK12, and further discusses the use of completable future.
Examples of this article https://github.com/ddean2009/ learn-java-base-9-to-20
Author of this article: the flydean program
Link to this article: http://www.flydean.com/jdk11-http-api/
Source: flydean's blog
Welcome to my official account: the procedures, the more wonderful things waiting for you!