Simple Get example

In this post under WebClient, I will show with example how to make a simple GET 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  
5  import reactor.core.publisher.Mono;
6  
7  public class Example1 {
8  	public static void main(String[] args) throws InterruptedException {
9  		WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
10 		Mono<String> mono = webClient.get()
11 				.uri("/users")
12 				.retrieve()
13 				.bodyToMono(String.class);
14 		mono.subscribe(value -> System.out.println(value));
15 		Thread.sleep(1000);
16 	}
17 }

In the above code, at line 10, I create an instance of WebClient by calling static “create” and passing the base url of the website as parameter.

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<String>” 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.

Leave a comment