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.
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
HttpRequest
object with the request method as POST and by providing the request body data asString
. We will make use of Jackson'sObjectMapper
to convert the request body,Map<String, String>
, into a plain JSONString
and then make use ofHttpRequest.BodyPublishers
to process theString
request body:
ObjectMapper mapper =newObjectMapper(); HttpRequest request =HttpRequest ...