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 ofÂjava.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...