Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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).
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();
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.