Java 9 : HTTP POST request example

1. Create an instance of HttpClient using its HttpClient.Builder builder:

HttpClient client = HttpClient.newBuilder().build();

2. Create the required data to be passed into the request body:
Map<String, String> requestBody =
Map.of("key1", "value1", "key2", "value2");

3. 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.fromString(
mapper.writeValueAsString(requestBody)))
.version(HttpClient.Version.HTTP_1_1).build();

4. The request is sent and the response is obtained by using the send(HttpRequest,
HttpRequest.BodyHandler) method:

HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandler.asString());

5. We then print the response status code and the response body sent by the server:

System.out.println("Status code: " + response.statusCode());
System.out.println("Response Body: " + response.body());

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation