Accessing HTML pages using asynchronous GET

To receive a response asynchronously, you can use the HttpClient sendAsync() method. This request will immediately return CompletableFuture. You can call the get() method on CompletableFuture to retrieve the response.

Let's modify the example used in the preceding section to receive the response (HTML text) in a file in an asynchronous manner:

class AsyncGetHTMLToFile { 
    public static void main(String args[]) throws Exception { 
        HttpClient client = HttpClient.newHttpClient(); 
        HttpRequest request = HttpRequest.newBuilder() 
        .uri(URI.create("https://docs.oracle.com/en
/java/javase/11/docs/api/java.net.http/java/net
/http/HttpClient.html")) .build(); CompletableFuture<Path> response = client.sendAsync(request,
BodyHandlers.ofFile(Paths.get("http.html"))) .thenApply(HttpResponse::body); response.get(); } }

BodyHandlers.ofFile() is an implementation of the BodyHandler interface, which uses BodySubscriber (a Reactive Stream) to subscribe to the body response bytes. Upon receiving the response body, it writes it to the specified file.

With the HTTP GET request, you can also include a set of parameter names and their values as a part of the URI. For example, by defining the URI as http://www.eJavaGuru.com/Java11.html?name="Mala", a client can pass the Mala value to the parameter name.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.133.54