In this post under Spring WebClient, I will explain with example how to set headers before making a HTTP call.
Below is the complete code for your reference
Main class
1 package defaultPackage;
2
3 import org.springframework.web.reactive.function.client.ClientResponse;
4 import org.springframework.web.reactive.function.client.WebClient;
5
6 import reactor.core.publisher.Mono;
7
8 public class Example5 {
9 public static void main(String[] args) throws Exception {
10 WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
11 Mono<String> mono = webClient.get()
12 .uri("/users")
13 .header("accept-language", "en-US")
14 .retrieve()
15 .bodyToMono(String.class);
16 mono.subscribe(value -> System.out.println(value));
17 Thread.sleep(1000);
18 }
19 }
In the above code, at line 10 I create an instance of “WebClient” class by calling static “create” method and passing the base url as its parameter.
From 11 to 15, I perform the following actions
1) configuring the “WebClient” instance to place a GET request by calling “get” method.
2) configuring the remaining section of the url by calling the “uri” method
3) adding header information by calling “header” method and passing the key and value as its parameter
4) calling the “retrieve” method to get the response body
5) calling the “bodyToMono” method to convert the respone body to an instance of “Mono” class.
At line 16, I call the “subscribe” method. At this point the actual get request is sent.
At line 17, I wait for one sec to get the response. This is not required in production code.
In this way we can set http headers.