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).
Setting Response Headers from Servlets The most general way to specify headers is to use the setHeader method of HttpServletResponse. This method takes two strings: the header name and the header value. As with setting status codes, you must specify headers before returning the actual document.
Interface WebTestClient. public interface WebTestClient. Client for testing web servers that uses WebClient internally to perform requests while also providing a fluent API to verify responses. This client can connect to any server over HTTP, or to a WebFlux application via mock request and response objects.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With