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

后端 未结 2 559
夕颜
夕颜 2021-01-04 01:30

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 02:12

    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 mono = client.get()
                ...
                .exchange()
                .flatMap(response -> response.bodyToMono(ByteArrayResource.class))
                .map(ByteArrayResource::getByteArray);
    

提交回复
热议问题