spring-bootjava-8resttemplaterest-clientspring-webclient

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?


Solution

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