I am testing a new WebClient from Spring 5 (5.0.0.RC2) in a code base using reactive programming, and I have had a successful mapping of the JSON response to the endpoint on the DTO in my application, which works very well:
WebClient client = WebClient.create(baseURI); Mono<DTO> dto = client.get() .uri(uri) .accept(MediaType.APPLICATION_JSON) .exchange() .flatMap(response -> response.bodyToMono(DTO.class));
However, now I am trying to get the response body from an endpoint using protocol buffers (binary data that are served as application/octet-stream ), so I would like to get the raw bytes from the response, which I then map the object to itself.
I decided that this would work using Bytes from Google Guava:
Mono<byte[]> bytes = client.get() .uri(uri) .accept(MediaType.APPLICATION_OCTET_STREAM) .exchange() .flatMapMany(response -> response.body(BodyExtractors.toDataBuffers())) .map(dataBuffer -> { ByteBuffer byteBuffer = dataBuffer.asByteBuffer(); byte[] byteArray = new byte[byteBuffer.remaining()]; byteBuffer.get(byteArray, 0, bytes.length); return byteArray; }) .reduce(Bytes::concat)
This works, but is there an easier and more elegant way to get these bytes?
source share