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
HttpClient
using itsHttpClient.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
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 ...