In this post under Spring WebClient, I show with example how to receive a user defined Java object as a response of GET request.
In all my previous post under Spring WebClient, I used to received data of type String class as part of GET request. Now in this example I will receive a user defined object instead of String object. There
is no difference between the two approaches. You have to place user defined object whereever String object was used.
For our example I will use the below Java class whose instance will be received as part of GET request.
ToDo class
package defaultPackage;
public class ToDo {
public int id;
public int userId;
public String title;
public boolean completed;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
...
@Override
public String toString() {
return "defaultPackage.ToDo{" +
"id=" + id +
", userId=" + userId +
", title='" + title + '\'' +
", completed=" + completed +
'}';
}
}
In the above “ToDo” class, we have 4 private fields (i.e., id, userId, title, completed) with their getter and setters. I have override the “toString” method.
Now lets see the main class where we will use the WebClient to send and receive a GET request.
Main class
1 package defaultPackage;
2
3 import org.springframework.http.MediaType;
4 import org.springframework.web.reactive.function.client.WebClient;
5 import reactor.core.publisher.Mono;
6
7 public class Example9 {
8 public static void main(String[] args) throws Exception {
9 WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
10 Mono<ToDo> mono = webClient.get()
11 .uri("/todos/1")
12 .accept(MediaType.APPLICATION_JSON)
13 .retrieve().bodyToMono(ToDo.class);
14 mono.subscribe(value -> {
15 System.out.println(value);
16 });
17 Thread.sleep(1000);
18 }
19 }
20
In the above code, at line 9, I create an instance of WebClient by calling static “create” and passing the base url of the website as parameter.
The url “https://jsonplaceholder.typicode.com/todos/1” returns a JSON data as response body which will be converted by Webclient to an instance of “ToDo” class internally.
From line 10 to 13, I performing the below tasks
1) Configuring the WebClient instance for GET request by calling “get” method
2) Configuring the remaining url by calling “uri” method
3) Calling the “retrieve” method to get the response body
4) Calling the “bodyToMono” method to convert the body to an instance of “Mono<ToDo>” class.
At line 14, I am calling the “subscribe” method on “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 15, I wait for 1 sec to get the response. This is not required in production code.
In this way we can make an GET HTTP call using WebClient and receive a user defined Java object.