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.HttpClient
using its builder,java.net.http.HttpClient.Builder
:
HttpClient client =HttpClient.newBuilder().build();
- Create an instance of
java.net.http.HttpRequest
using 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
send
API ofjava.net.http.HttpClient
. This API takes an instance ofjava.net.http.HttpRequest
and an implementation ofjava.net.http.HttpResponse.BodyHandler
:
HttpResponse<String> response = client.send(request, HttpResponse...