Before diving into the details of the individual classes of the HTTP Client, I'm including a basic example to let you get a hang of sending a request to a server and processing the response using the HTTP Client. I'll add to this example as we move forward, covering HttpClient, HttpRequest, and HttpResponse in detail. This is to help you get the bigger picture and then dive into the details.
The following example shows how to create a basic HttpClient instance, use it to access a URI encapsulated by HttpRequest, and process the response, accessible as a HttpResponse instance:
// basic HttpClient instance HttpClient client = HttpClient.newHttpClient(); // Using builder pattern to get a basic HttpRequest instance with just //the URI HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://www.ejavaguru.com/")) .build(); // response instance not created using a builder. // HttpClient sends HttpRequests and makes HttpResponse available HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());
In the preceding code, the newHttpClient() factory method returns a basic HttpClient instance, which can be used to send an HTTP request and receive its corresponding response. HttpRequest is created using the builder pattern by passing it the URI to connect with (which is the minimum requirement). The HttpResponse instance is not created explicitly by a developer but is received after a request is sent from HttpClient to a server.
The send() method sends the request synchronously and waits for the response. When the client receives the response code and headers, it invokes BodyHandler before the response body is received. Upon invocation, BodyHandler creates BodySubscriber (a Reactive Stream subscriber), which receives the streams of response data from the server and converts them to an appropriate higher-level Java type.
If you didn't understand the preceding explanation completely, don't worry; I'll cover this in detail in the following sections.
Let's dive into the details, starting with the HttpClient class.