Search code examples
javaspring-bootspring-webfluxspring-webclient

Getting some httpHeader in spring webclient call


In my spring boot 2.4.1 application, I'm using WebClient for invoking some external rest services.

In reqular scenario it's pretty straightforward and works fine as I expected:

InquiryChequeResponse  response=webClient.post()
    .uri(inquiryChequeUrl)
    .body(Mono.just(requestDto), InquiryChequeReq.class)
    .exchangeToMono(res -> {
            return res.bodyToMono(InquiryChequeResponse.class);
    }).block();

But I need to get some values like "requestTraceId" from response headers and update the final response. I tried like this :

InquiryChequeResponse  response=webClient.post()
    .uri(inquiryChequeUrl)
    .body(Mono.just(requestDto), InquiryChequeReq.class)
    .exchangeToMono(res -> {
            String requestTraceId= res.headers().asHttpHeaders().getFirst("requestTraceId");
            Mono<InquiryChequeResponse> inquiryCheque= res.bodyToMono(InquiryChequeResponse.class);
            inquiryCheque.block().setRequestTraceId(requestTraceId);
            return inquiryCheque;
    }).block();

But I get following exception :

block()/blockFirst()/blockLast() are blocking, whichis not supported in thread reactor-http-nio-2

My question is what's wrong and how can I get some specific request header and include it in my final response?


Solution

  • Instead of trying to wait on the Mono and then working with the contents you should use the methods on Mono and supply functions (or lambdas) that manipulate it's contents.

    In your case you want to use map.

        .exchangeToMono(res -> {
                String requestTraceId = res.headers().asHttpHeaders().getFirst("requestTraceId");
                return res
                    .bodyToMono(InquiryChequeResponse.class)
                    .map(ic -> {
                        ic.setRequestTraceId(requestTraceId);
                        return ic;
                    });
        })