Accessing HTML pages using synchronous GET

HttpClient can receive a response from a server in either a synchronous or asynchronous manner. To receive a response synchronously, use the HttpClient method, send(). This request will block the thread until the response is completely received.

The following code connects to Oracle's web server that hosts the API documentation of the HttpClient class, using a GET request sent synchronously:

class SyncGetHTML { 
    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(); HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); System.out.println(response.body()); } }

The preceding code generates a lot of text. The following are just a few initial lines from the output:

<!DOCTYPE HTML> 
<!-- NewPage --> 
<html lang="en"> 
<head> 
<!-- Generated by javadoc --> 
<title>HttpClient (Java SE 11 & JDK 11 )</title> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<meta name="keywords" content="java.net.http.HttpClient class"> 

The preceding code receives the HTML data as a string since it passes BodyHandlers.ofString() to the send() method. The variable used for the reception of this response is the HttpResponse<String> instance that matches with the response body subscriber (BodyHandlers.ofString()) used to process the response body bytes.

Let's see what happens if we store the response from the preceding request as a .html file. Here's the modified code:

class SyncGetHTMLToFile { 
    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(); HttpResponse<Path> response = client.send(request,
BodyHandlers.ofFile(Paths.get("HttpClient.html"))); } }

In the preceding code, the content of HttpClient.html is the same as the text that is sent to the console in the previous example. In this example, the response body bytes are written to a file.

Since the file is saved as a .html file, you can view it in your web browser. However, the display of this file won't match with the display of the hosted HttpClient class, because your local .html file can't access .css or other hosted styles used by HttpClient.html.

The following screenshot compares the rendering of the local and hosted HttpClient.html:

Let's modify the preceding example to receive the response asynchronously.

..................Content has been hidden....................

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