JaeYoung Lee
JaeYoung Lee

Reputation: 145

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

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).

Upvotes: 11

Views: 17975

Answers (1)

Ilya Zinkovich
Ilya Zinkovich

Reputation: 4410

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

Upvotes: 26

Related Questions