How to set multiple headers at once in Spring WebClient?

Amit Kumar picture Amit Kumar · Dec 2, 2019 · Viewed 14.3k times · Source

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?

Answer

Brian Clozel picture Brian Clozel · Dec 5, 2019

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();