如何从Spring WebClient的ClientResponse中获取最佳字节数组? [英] How to best get a byte array from a ClientResponse from Spring WebClient?
问题描述
我在Spring 5(5.0.0.RC2)中尝试使用反应式编程的代码库中的新 WebClient
,并且我已经成功映射了JSON从我的应用程序中的端点到DTO的响应非常好:
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));
但是,现在我正在尝试使用协议缓冲区(二进制数据)的端点的响应主体作为 application / octet-stream
),所以我想从响应中获取原始字节,然后我将自己映射到一个对象。
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.
我使用来自Google Guava的 Bytes
这样工作:
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?
推荐答案
ClientResponse.bodyToMono()
最后使用了一些 org.springframework.core.codec声明支持指定类的.Decoder
。
所以我们应该检查解码器的类层次结构
,特别是 decodeToMono()
的地点和方式方法已实现。
So we should check the class hierarchy of the Decoder
, in particular where and how the decodeToMono()
method is implemented.
有一个 StringDecoder
支持解码为 String
,一堆与Jackson相关的解码器(在你的DTO示例中使用),还有一个特别感兴趣的 ResourceDecoder
。
There is a StringDecoder
which supports decoding to String
, a bunch of Jackson-related decoders (used in your DTO example under the hood), and there is also a ResourceDecoder
which is of particular interest.
ResourceDecoder
支持 org.springframework.core.io.InputStreamResource
和 org.springframework.core.io.ByteArrayResource
。 ByteArrayResource
本质上是 byte []
的包装器,因此以下代码将提供对响应主体的访问,字节数组:
ResourceDecoder
supports org.springframework.core.io.InputStreamResource
and org.springframework.core.io.ByteArrayResource
. ByteArrayResource
is essentially a wrapper around byte[]
, so the following code will provide an access to the response body as a byte array:
Mono<byte[]> mono = client.get()
...
.exchange()
.flatMap(response -> response.bodyToMono(ByteArrayResource.class))
.map(ByteArrayResource::getByteArray);
这篇关于如何从Spring WebClient的ClientResponse中获取最佳字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!