O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Create an instance of HttpClient using its builder, HttpClient.Builder:
        HttpClient client = HttpClient.newBuilder().build();
  1. Create an instance of HttpRequest using its HttpRequest.Builder builder, representing the URL and the corresponding HTTP method to be used:
        HttpRequest request = HttpRequest                        .newBuilder(new URI("http://httpbin.org/get"))                        .GET()                        .version(HttpClient.Version.HTTP_1_1)                        .build();
  1. Use the sendAsync method to make an asynchronous HTTP request and keep a reference to the CompletableFuture<HttpResponse<String>> object thus obtained. We will use this to process the response:
        CompletableFuture<HttpResponse<String>> responseFuture =                   client.sendAsync(request,                          HttpResponse.BodyHandler.asString());
  1. We provide ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required