Triggering asynchronous GET request is a three-step job, as follows:
- Create a new HttpClient object (java.net.http.HttpClient):
HttpClient client = HttpClient.newHttpClient();
- Build an HttpRequest object (java.net.http.HttpRequest) and specify the request (by default, this is a GET request):
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
For setting the URI, we can call the HttpRequest.newBuilder(URI) constructor or call the uri(URI) method on the Builder instance (like we did previously).
- Trigger the request and wait for the response (java.net.http.HttpResponse). Being a synchronous request, the application will block until the response is available:
HttpResponse<String> response
= client.send(request, BodyHandlers.ofString());
If we group these three steps and add the lines for displaying the response code and body at the console, then we obtain the following code:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
HttpResponse<String> response
= client.send(request, BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println(" Body: " + response.body());
One possible output for the preceding code is as follows:
Status code: 200
Body:
{
"data": {
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://s3.amazonaws.com/..."
}
}
By default, this request takes place using HTTP/2. However, we can explicitly set the version via HttpRequest.Builder.version() as well. This method gets an argument of the HttpClient.Version type, which is an enum data type that exposes two constants: HTTP_2 and HTTP_1_1. The following is an example of explicitly downgrading to HTTP/1.1:
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
The default settings for HttpClient are as follows:
- HTTP/2
- No authenticator
- No connection timeout
- No cookie handler
- Default thread pool executor
- Redirection policy of NEVER
- Default proxy selector
- Default SSL context
We'll take a look at the query parameter builder in the next section.