如何处理 Spring WebClient get application/octet-stream as body InputStream?

How to handle Spring WebClient get application/octet-stream as body InputStream?

我正在使用 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(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(BodyExtractors.java:92)

......

我在 spring-webflux 5.0.7。

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

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

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

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