1

I am downloading files using Spring WebClient like below:

private void dnloadFileAPI(String theId, String destination) {
        log.info("Downloading file.. " + theId);
        Flux<DataBuffer> dataBuffer = webClient
                .get()
                .uri("/some/fancy/" + theId + "/api")
                .retrieve()
                .onStatus(HttpStatus::is2xxSuccessful, response -> Mono.just(new CustomException("Success")))
                .bodyToFlux(DataBuffer.class);
        DataBufferUtils.write(dataBuffer, Paths.get(destination), StandardOpenOption.CREATE).share().block();
    }

File(s) get downloaded fine. The only piece I am struggling is, when the response is 200, I just want to log one line like this:

log.info("{}", theId + " - File downloaded successfully")

I tried this too but didnt get what I am looking for - How to log Spring WebClient response

In short, is there some way above can be achieved without writing a separate CustomException ? Feeling lost and clueless here. Any pointers in this regard will be highly appreciated.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35
Ajay Kumar
  • 2,906
  • 3
  • 23
  • 46

2 Answers2

1

I think adding the following after the bodyToFlux(DataBuffer.class) line will be what you need

.doOnComplete(() -> log.info("File downloaded successfully"))

Something like this

private void dnloadFileAPI(String theId, String destination) {
    log.info("Downloading file.. " + theId);
    Flux<DataBuffer> dataBuffer = webClient
        .get()
        .uri("/some/fancy/" + theId + "/api")
        .retrieve()
        .bodyToFlux(DataBuffer.class)
        .doOnComplete(() -> log.info("File downloaded successfully"));
    DataBufferUtils.write(dataBuffer, Paths.get(destination), StandardOpenOption.CREATE).share().block();
}
athom
  • 1,428
  • 4
  • 13
  • 26
  • Dang...!! so much to learn !!! `.doOnComplete(..)` was exactly I was looking for. ! I don't need `.onStatus(...)` now. Thanks a million @athom. – Ajay Kumar Oct 14 '21 at 02:00
0

We can used doOnSuccess method

.doOnSuccess(response -> logger.info("File downloaded successfully"))

Spring-webflux version 5.3.22

SANN3
  • 9,459
  • 6
  • 61
  • 97