Making an HTTP GET request
In this recipe, we will look at using the JDK 11 HTTP Client API to make a GET request to http://httpbin.org/get.
How to do it...
- Create an instance of
java.net.http.HttpClientusing its builder,Âjava.net.http.HttpClient.Builder:
HttpClient client =HttpClient.newBuilder().build();
- Create an instance ofÂ
java.net.http.HttpRequestusing its builder,Âjava.net.http.HttpRequest.Builder. The requested URL should be provided as an instance ofjava.net.URI:
HttpRequest request =HttpRequest
.newBuilder(newURI("http://httpbin.org/get"))
.GET()
.version(HttpClient.Version.HTTP_1_1)
.build();- Send the HTTP request using the
sendAPI ofÂjava.net.http.HttpClient. This API takes an instance ofjava.net.http.HttpRequestand an implementation ofjava.net.http.HttpResponse.BodyHandler:
HttpResponse<String> response = client.send(request,
HttpResponse...