Spring Webclient decode custom application/multipart-related,application/dicom (Wado-RS)

853 views Asked by At

I'm trying to decode a multipart-related request that is just a simple multi files download but with a specific content type by part (application/dicom and not application/octet-stream). Since the structure of the response body might be identical, I could just tell the "multipart codec" to treat that content type as an octet-stream.

public Flux<FilePart> getDicoms(String seriesUri) {
    return webClient.get()
            .uri(seriesUri)
            .accept(MediaType.ALL)
            .retrieve()
            .bodyToFlux(FilePart.class);
}

How can I do that?

2

There are 2 answers

1
Romanow On BEST ANSWER

An easier way of reading a multipart response:

private Mono<ResponseEntity<Flux<Part>>> queryForFiles(String uri)
    final var partReader = new DefaultPartHttpMessageReader();
    partReader.setStreaming(true);
    
    return WebClient.builder()
            .build()
            .get()
            .uri(wadoUri)
            .accept(MediaType.ALL)
            .retrieve()
            .toEntityFlux((inputMessage, context) -> partReader.read(ResolvableType.forType(DataBuffer.class), inputMessage, Map.of())))
0
Saveriu CIANELLI On

This is what I've done to make it work. I used directly the DefaultPartHttpMessageReader class to do it cleanly (spring 5.3).

public Flux<Part> getDicoms(String wadoUri) {
    final var partReader = new DefaultPartHttpMessageReader();
    partReader.setStreaming(true);
    return WebClient.builder()
            .build()
            .get()
            .uri(wadoUri)
            .accept(MediaType.ALL)
            //.attributes(clientRegistrationId("keycloak"))
            .exchange()
            .flatMapMany(clientResponse -> {
                var message = new ReactiveHttpInputMessage() {
                    @Override
                    public Flux<DataBuffer> getBody() {
                        return clientResponse.bodyToFlux(DataBuffer.class);
                    }

                    @Override
                    public HttpHeaders getHeaders() {
                        return clientResponse.headers().asHttpHeaders();
                    }
                };
                return partReader.read(ResolvableType.forType(DataBuffer.class), message, Map.of());

            });
}