Making an HTTP POST request
In this recipe, we will look at posting some data to an HTTP service via the request body. We will post the data to the http://httpbin.org/post URL.
Note
We will skip the package prefix for the classes, as it is assumed to be java.net.http.
Â
How to do it...
- Create an instance of
HttpClientusing itsÂHttpClient.Builder builder:
HttpClient client =HttpClient.newBuilder().build();
- Create the required data to be passed into the request body:
Map<String, String> requestBody =
Map.of("key1", "value1", "key2", "value2");- Create a
HttpRequestobject with the request method as POST and by providing the request body data asString. We will make use of Jackson'sÂObjectMapperto convert the request body,ÂMap<String, String>, into a plain JSONÂStringand then make use ofHttpRequest.BodyPublishersto process theStringrequest body:
ObjectMapper mapper =newObjectMapper();
HttpRequest request =HttpRequest
...