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

Meo*_*ode 6 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));
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪的一部分。

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)
Run Code Online (Sandbox Code Playgroud)

......

我使用的是 spring-webflux 5.0.7。

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

JB *_*zet 4

不是专家,但您可以使用以下方法获取Flux<byte[]>每个已发布数组将包含响应正文的切片的位置,而不是输入流)

.get()
.uri(uri)
.accept(MediaType.APPLICATION_OCTET_STREAM)
.retrieve()
.bodyToFlux(byte[].class)
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你的回答。这既帮助我解决了我的问题...并确定使用非反应式 HTTP 客户端更有意义。所以谢谢你两次! (4认同)