How to best get a byte array from a ClientResponse from Spring WebClient?

主宰稳场 提交于 2019-12-04 00:14:25

ClientResponse.bodyToMono() in the end uses some org.springframework.core.codec.Decoder which claims to support the specified class.

So we should check the class hierarchy of the Decoder, in particular where and how the decodeToMono() method is implemented.

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 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!