Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set multiple headers at once in Spring WebClient?

I was trying to set headers to my rest client but every time I have to write

webclient.get().uri("blah-blah")
         .header("key1", "value1")
         .header("key2", "value2")...

How can I set all headers at the same time using headers() method?

like image 858
Amit Kumar Avatar asked Dec 02 '19 06:12

Amit Kumar


1 Answers

If those headers change on a per request basis, you can use:

webClient.get().uri("/resource").headers(httpHeaders -> {
    httpHeaders.setX("");
    httpHeaders.setY("");
});

This doesn't save much typing; so for the headers that don't change from one request to another, you can set those as default headers while building the client:

WebClient webClient = WebClient.builder().defaultHeader("...", "...").build();
WebClient webClient = WebClient.builder().defaultHeaders(httpHeaders -> {
    httpHeaders.setX("");
    httpHeaders.setY("");
}).build();
like image 64
Brian Clozel Avatar answered Sep 17 '22 11:09

Brian Clozel