Search code examples
springwebclientspring-webfluxproject-reactor

How to compile answer from multiple requests with Spring WebClient


I want to make a proxy controller. I get a single HTTP request and I need to proxy it to other services, then compile answers from responses into one and send it back. If one response contains an exception, ResponseEntity shouldn't be with code 200(OK).

@PostMapping("**")
public ResponseEntity<String> processIn(@RequestHeader HttpHeaders headers, @RequestBody String body,  ServerHttpRequest request) {

    Mono<String> firstAnswer = sendRequest(headers, body, "https://localhost:1443");
    Mono<String> secondAnswer = sendRequest(headers, body, "http://localhost:8080");

    return ResponseEntity.ok().body(format("1: %s \n 2: %s", firstAnswer, secondAnswer));
}

private Mono<String> sendRequest(HttpHeaders headers, String body, String url) {
        return webClient.post()
                .uri(new URI(url))
                .headers(httpHeaders -> new HttpHeaders(headers))
                .bodyValue(body)
                .retrieve()
                .bodyToMono(String.class)
                .doOnNext(ans -> log.info(">>>>request to {} : {}", url, ans))
                .doOnError(err -> log.error(">>>>error sending to {}", url));
    }

Solution

  • You can try something like this. I used 'block' here as you wanted to return ResponseEntity directly.

    firstAnswer.zipWith(secondAnswer)
            .map(tuple -> String.format("1: %s \n 2: %s", tuple.getT1(), tuple.getT2()))
            .map(ResponseEntity::ok)
            .onErrorReturn(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build())
            .block();
    

    Instead you could remove the block by changing the return type to Mono<ResponseEntity>

    firstAnswer.zipWith(secondAnswer)
            .map(tuple -> String.format("1: %s \n 2: %s", tuple.getT1(), tuple.getT2()))
            .map(ResponseEntity::ok)
            .onErrorReturn(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());