【问题标题】:How to handle Spring WebClient get application/octet-stream as body InputStream?如何处理 Spring WebClient 获取 application/octet-stream 作为 body InputStream?
【发布时间】:2019-06-13 16:22:07
【问题描述】:

我正在使用 GET 请求下载文件。其中一些非常大,所以我想将它们作为流获取并读取块中的字节,因为我可以处理它们,从不读取内存中的整个文件。

org.springframework.web.reactive.function.client.WebClient 看起来很合适,但我遇到了“UnsupportedMediaTypeException:不支持内容类型'application/octet-stream'。

这是一些简短的示例代码。

@Autowired WebClient.Builder webClientBuilder;
....
ClientResponse clientResponse = webClientBuilder.clientConnector(this.connector)
.build()
.get()
.uri(uri)
.accept(MediaType.APPLICATION_OCTET_STREAM)
.exhange()
.block(Duration.of(1, ChronoUnit.MINUTES));

// blows up here, inside of the body call
InputStream responseInputStream = clientResponse.body(BodyExtractors.toMono(InputStream.class)).block(Duration.of(1, ChronoUnit.MINUTES));

这是堆栈跟踪的一部分。

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/octet-stream' not supported
   at org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$20(BodyExtractors.java:254)
   at java.util.Optional.orElseGet(Optional.java:267)
   at org.springframework.web.reactive.function.BodyExtractors.readWithMessageReaders(BodyExtractors.java:250)
   at org.springframework.web.reactive.function.BodyExtractors.lambda$toMono$2(BodyExtractors.java:92)

......

我使用的是 spring-webflux 5.0.7。

我确信 spring webclient 必须支持 JSON 之外的东西。我只是不知道该怎么做。帮忙?

【问题讨论】:

    标签: spring spring-webflux


    【解决方案1】:

    不是专家,但不是 InputStream,您可以获得 Flux<byte[]>,其中每个发布的数组将包含响应正文的一部分),使用

    .get()
    .uri(uri)
    .accept(MediaType.APPLICATION_OCTET_STREAM)
    .retrieve()
    .bodyToFlux(byte[].class)
    

    如果您愿意,也可以使用 ByteBuffer 而不是 byte[] 执行相同的操作。

    【讨论】:

    • 感谢您的回答。这都帮助我解决了我的问题......并确定使用非反应式 HTTP 客户端更有意义。所以谢谢你两次!
    • @MeowCode 您使用了什么非反应式 HTTP 客户端,您可以分享相同的示例代码吗?我有类似的要求,我需要处理服务发送的字节 [] 作为响应。
    猜你喜欢
    • 2021-07-09
    • 2022-08-09
    • 2012-03-31
    • 1970-01-01
    • 2013-04-12
    • 2014-06-08
    • 2020-03-30
    • 2014-11-25
    • 2012-04-16
    相关资源
    最近更新 更多