In this post under WebClient, I will show with example how to make a simple POST HTTP request using WebClient framework.
Below is the complete main method for your reference
Main class
1 package defaultPackage;
2
3 import org.springframework.web.reactive.function.client.WebClient;
4 import reactor.core.publisher.Mono;
5
6 public class Example2 {
7 public static void main(String[] args) throws InterruptedException {
8 String data = "{\r\n" +
9 " \"title\": \"morpheus\",\r\n" +
10 " \"body\": \"leader\",\r\n" +
11 " \"userId\": 1\r\n" +
12 "}";
13 WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
14 Mono<String> response = webClient.post()
15 .uri("/posts")
16 .bodyValue(data)
17 .retrieve()
18 .bodyToMono(String.class);
19 response.subscribe(value -> {
20 System.out.println(value);
21 });
22 Thread.sleep(3000);
23 }
24 }
In the above code, at line 10, I create the data that I want to post.
At line 13, I create an instance of WebClient by calling static “create” and passing the base url of the website as parameter.
From line 14 to 18, I performing the below tasks
1) Configuring the WebClient instance for POST request by calling “post” method
2) Configuring the remaining url by calling “uri” method
3) Configuring the data to be posted by calling “bodyValue” method
4) Calling the “retrieve” method to get the response bodyValue
5) Calling the “bodyToMono” method to convert the body to an instance of “Mono<String>” class.
At line 19, I am calling the “subscribe” method of “Mono” instance and passing a functional interface which will print the value to the console.
When the “subscribe” method is called, the WebClient framework makes an actual api call to the server.
For our example, at line 22, I wait for 3 sec to get the response. This is not required in production code.
In this way we can make an POST HTTP call using WebClient.