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 HttpClient.Builder builder:
        HttpClient client = HttpClient.newBuilder().build();
  1. Create the required data to be passed into the request body:
        Map<String, String> requestBody =                     Map.of("key1", "value1", "key2", "value2");
  1. Create a HttpRequest object with the request method as POST and by providing the request body data as String. We make use of Jackson's ObjectMapper to convert the request body, Map<String, String>, into a plain JSON String and then make use of HttpRequest.BodyProcessor to process the String request body:
        ObjectMapper mapper = new ObjectMapper();        HttpRequest request = HttpRequest                   .newBuilder(new URI("http://httpbin.org/post"))                   .POST(          HttpRequest.BodyProcessor ...

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