Setting accept header example

In this post under Spring WebClient, I will explain with example how to set “ACCEPT” header before sending an HTTP GET request.

Below is the complete main code for your reference.

Main class

1  package defaultPackage;
2  
3  import org.springframework.http.MediaType;
4  import org.springframework.web.reactive.function.client.ClientResponse;
5  import org.springframework.web.reactive.function.client.WebClient;
6  
7  import reactor.core.publisher.Mono;
8  
9  public class Example6 {
10 	public static void main(String[] args) throws Exception {
11 		WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");
12 		Mono<String> mono = webClient.get()
13 				.uri("/users")
14 				.accept(MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE))
15 				.retrieve()
16 				.bodyToMono(String.class);
17 		mono.subscribe(value -> System.out.println(value));
18 		Thread.sleep(1000);
19 	}
20 }

In the above code, at line 11, I created an instance of “WebClient” class by calling static “create” method and passing the base url as a parameter.

From line 12 to 16, I perform the below operations.
1) configure the WebClient instance for GET request by calling “get” method
2) configure the remaining part of the url by calling the “uri” method
3) configure the ACCEPT header by calling “accept” method and passing the media type as a parameter
4) calling the “retrieve” method to get the response body
5) calling the “bodyToMono” method to convert the response body to an instance of “Mono<String>” class

At line 17, we call “subscribe” method. At that time the actual request is made.

At line 18, for our example we wait for 1 sec. This is not required for production code.

In this way we set the accept header.

Leave a comment