如何处理Spring WebClient获取应用程序/八位字节流作为主体InputStream?

时间:2019-06-13 16:22:07

标签: spring spring-webflux

我正在下载带有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以外的东西。我只是不知道该怎么做。帮助吗?

1 个答案:

答案 0 :(得分:2)

不是专家,而是使用Inputs而不是InputStream,可以使用{p>在其中每个发布的数组将包含响应正文的一部分的地方Flux<byte[]>

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

如果愿意,您也可以使用ByteBuffer来代替byte[]