java - Spring Web 客户端 : How to stream large byte[] to file?

标签 java spring spring-webflux project-reactor spring-webclient

好像是 Spring RestTemplate如果不将响应全部缓冲在内存中,则无法将响应直接流式传输到文件。使用较新的 Spring 5 WebClient 实现此目的的正确方法是什么? ?

WebClient client = WebClient.create("https://example.com");
client.get().uri(".../{name}", name).accept(MediaType.APPLICATION_OCTET_STREAM)
                    ....?

我看到人们已经通过 RestTemplate 找到了解决此问题的一些解决方法/技巧,但我更感兴趣的是使用 WebClient 以正确的方式进行操作.

有很多使用RestTemplate的例子下载二进制数据,但几乎所有数据都会加载 byte[]进入内存。

最佳答案

使用最近稳定的 Spring WebFlux(撰写本文时为 5.2.4.RELEASE):

final WebClient client = WebClient.create("https://example.com");
final Flux<DataBuffer> dataBufferFlux = client.get()
        .accept(MediaType.TEXT_HTML)
        .retrieve()
        .bodyToFlux(DataBuffer.class); // the magic happens here

final Path path = FileSystems.getDefault().getPath("target/example.html");
DataBufferUtils
        .write(dataBufferFlux, path, CREATE_NEW)
        .block(); // only block here if the rest of your code is synchronous

对我来说,不明显的部分是 bodyToFlux(DataBuffer.class),因为它目前在 generic section about streaming 中提到。在 Spring 的文档中,WebClient 部分没有直接引用它。

关于java - Spring Web 客户端 : How to stream large byte[] to file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56210186/

相关文章:

java - 如何在不使用 split 方法或使用数组的情况下将字符串拆分为单词?

java - 无法运行简单的项目(Maven - Spring - Eclipse)

java - 在非实体 java bean 中映射多个 hibernate 实体

java - 使用 hibernate 连接不同数据库中的两个表

java - 当 flatMap 返回空 Mono 时如何调用 switchIfEmpty?

带有 Springs ResponseEntity 的 Kotlin 和通用返回类型

Spring Boot WebClient.Builder bean 在传统 servlet 多线程应用程序中的使用

java - 使用 JOGL(Java OpenGL)

java - 在特定时间执行java代码

java - 无法使用 Android PhotoView Activity