I'm trying out the new WebClient
from Spring 5 (5.0.0.RC2) in a codebase that uses reactive programming and I've had success mapping the JSON response from an endpoint to a DTO in my app, which works very nice:
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'm trying to the response body from an endpoint which uses Protocol Buffers (binary data served as application/octet-stream
), so I'd like to get the raw bytes from the response, which I'll then map to an object myself.
I got it to work like this 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, more elegant way to get these bytes?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…