gpt4 book ai didi

java - 使用Spring Webclient下载文件,文件为空

转载 作者:行者123 更新时间:2023-12-04 13:13:08 24 4
gpt4 key购买 nike

我应该从第 3 方 API 下载 ZIP 文件。但是,当我使用 Spring Webclient 时,我最终得到了一个空文件。任何想法我做错了什么?存储Flux<DataBuffer>内容的正确方法是什么?到一个文件?
这是我的代码:

WebClient client = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient1))
.baseUrl(String.format(FILE_DOWNLOAD_PATH))
.build();


WebClient.RequestBodyUriSpec method = client.method(HttpMethod.GET);
method.header("Authorization", "Bearer " + accessToken);
final Flux<DataBuffer> dataBufferFlux = method.retrieve().bodyToFlux(DataBuffer.class);

final Path path = FileSystems.getDefault().getPath("example" + new Random(200).nextInt() + ".zip");

WritableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
Mono<Path> then = DataBufferUtils.write(dataBufferFlux, channel)
.map(DataBufferUtils::release)
.then(Mono.just(path));
更新:上面的代码是直接从 main 调用的,然后应用程序关闭。这可能是一个问题吗?

最佳答案

正如@MichaelBerry 提到的,您错过了 block称呼。
method documentation中明确提到了那:Note that the writing process does not start until the returned Flux is subscribed to.下面的代码对我有用:

public class MySpringBootApp {

public static void main(String[] args) throws IOException {

Path path = Paths.get("src/main/resources/sample.zip");
WebClient client = WebClient.builder()
.baseUrl("https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip")
.build();
Flux<DataBuffer> dataBufferFlux = client.get().retrieve().bodyToFlux(DataBuffer.class);
DataBufferUtils.write(dataBufferFlux, path, StandardOpenOption.CREATE).block(); //Creates new file or overwrites exisiting file

}


}

关于java - 使用Spring Webclient下载文件,文件为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62898166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com