java - Spring WebClient 下载图像

标签 java reactive-programming spring-webflux

我一直在研究响应式编程,最近尝试使用 Spring WebFlux 构建 POC。我想从简单开始,只使用 WebClient 下载图像;具体来说https://greatatmosphere.files.wordpress.com/2013/02/great-atmosphere-149-tenaya-lake-yosemite-national-park-2.jpg

我尝试过以下代码

    String block = WebClient.create("https://greatatmosphere.files.wordpress.com/2013/02/great-atmosphere-149-tenaya-lake-yosemite-national-park-2.jpg")
            .get()
            .accept(MediaType.IMAGE_JPEG)
            .retrieve()
            .bodyToMono(String.class)
            .doOnError(WebClientResponseException.class,
                    ex -> System.out.println(ex.getStatusCode() + ": " + ex.getResponseBodyAsString()))
            .log()
            .block();
    System.out.println("output:" + block);

但它没有按预期工作。看起来数据在不断地流式传输并且获取请求不会终止。

我确信我错过了一些简单的东西,但我似乎无法弄清楚。我尝试了多种参数,但结果都是一样的。

如何使用 WebClient 下载图像然后终止?

最佳答案

将图像捕获为byte[]而不是String

byte[] image = WebClient.create("https://greatatmosphere.files.wordpress.com/2013/02/great-atmosphere-149-tenaya-lake-yosemite-national-park-2.jpg")
        .get()
        .accept(MediaType.IMAGE_JPEG)
        .retrieve()
        .bodyToMono(byte[].class)
        .block();

关于java - Spring WebClient 下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998855/

相关文章:

java - 使用 Spring data Mongo 搜索嵌入数组中的文本列表

r - 带有nearPoints()的动态ggplot图层 Shiny

c++ - 如何在自定义 rxcpp 运算符上调用 on_error

java - 如何在 Spring WebFlux 中从多个 Flux (WebsocketSession::receive) 正确向 Sink 发出值?

spring-boot - Spring WebFlux Security - 是否可以在 SecurityWebFilterChain 上为不同的资源配置多个 ServerAuthenticationEntryPoints

java - 为什么我不能在函数内使用 ManagedProperty ?

java - Spring JPA和Hibernate在调用save方法时不将实体保存到数据库

java - 如何在没有同步块(synchronized block)(即低成本锁)的情况下在一个安全操作中原子地检查 Java 中的两个 AtomicBooleans?

c# - MVVM、ObservableCollection 和 Reactive Extensions (Rx) 的跨线程访问无效

spring - 如何使用 Spring Boot Security 修复 Spring Boot Webflux 应用程序中的 'Invalid bean definition with name requestMappingHandlerAdapter' 错误