'webclient set header reactive way

I am new to WebFlux and reactive way of programming. I am using WebClient to call a REST service, when making the call, I need to set a HTTP header, the value for the HTTP header comes from a reactive stream, but the header method on the WebClient only takes String value...

Mono<String> getHeader() {
    ...
}

webClient
  .post()
  .uri("/test")
  .body(Mono.just(req),req.getClass())
  .header("myHeader",getHeader())
...

The above line won't compile, since header method takes an String for second argument. How can I set a header if the value comes from a reactive stream?



Solution 1:[1]

You just need to chain getHeader and web client request using flatMap to create reactive flow

return getHeader()
 .flatMap(header -> 
        webClient
           .post()
           .uri("/test")
           .header("myHeader", header)
           .body(BodyInserters.fromValue(req))
           ...
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex