Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 873
JaeYoung Lee Avatar asked May 14 '19 04:05

JaeYoung Lee


People also ask

How do you add a response header in Java?

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.

What is WebTestClient?

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.


1 Answers

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();
like image 108
Ilya Zinkovich Avatar answered Oct 20 '22 01:10

Ilya Zinkovich