好像是 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/