In this post under WebClient, I will show with example how to make a simple PUT 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 Example3 {
7 public static void main(String[] args) throws InterruptedException {
8 WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
9 String data = "{\r\n" +
10 " \"id\": 100,\r\n" +
11 " \"title\": \"morpheus1\",\r\n" +
12 " \"body\": \"leader\",\r\n" +
13 " \"userId\": 1\r\n" +
14 "}";
15 Mono<String> response = webClient.put()
16 .uri("/users/10")
17 .bodyValue(data)
18 .retrieve()
19 .bodyToMono(String.class);
20 response.subscribe(value -> System.out.println(value));
21 Thread.sleep(3000);
22 }
23 }
In the above code, at line 8, we create an instance of WebClient class by calling static “create” method and passing the base url.
At line 9, we create data that will be sent to the server.
From line 15 to 19, I performing the below tasks
1) Configuring the WebClient instance for PUT request by calling “put” 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 body.
5) Calling the “bodyToMono” method to convert the body to an instance of “Mono<String>” class.
At line 20, 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 21, I wait for 3 sec to get the response. This is not required for production code.
In this way we can make an POST HTTP call using WebClient.