TransWikia.com

Add a header to an outgoing request by a filter in WebFlux

Stack Overflow Asked by Jae Young Lee on February 1, 2021

I’m using Java Spring WebFlux for client and server, and I want to customize my request from client to server by adding a custom header to it. I’m already using WebFilter for another purpose, but it seems like it’s only working for incoming requests and responses (such as a request from FE and a response to it).

One Answer

There are multiple ways of specifying custom headers.

If the headers are static, you can specify them during WebClient instance creation using defaultHeader or defaultHeaders methods:

WebClient.builder().defaultHeader("headerName", "headerValue")
WebClient.builder().defaultHeaders(headers -> headers.add("h1", "hv1").add("h2", "hv2"))

If the headers are dynamic but the header value generation is common for all requests, you can use ExchangeFilterFunction.ofRequestProcessor configured during WebClient instance creation:

WebClient
    .builder()
    .filter(ExchangeFilterFunction.ofRequestProcessor(
        request -> Mono.just(ClientRequest.from(request)
                                          .header("X-HEADER-NAME", "value")
                                          .build())
    )
    .build();

If headers are dynamic and specific per each use of WebClient, you can configure headers per call:

webClient.get()
    .header("headerName", getHeaderValue(params))
    .retrieve();

Answered by Ilya Zinkovich on February 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP