java - 带有文本/html 响应的响应式(Reactive) WebClient GET 请求

标签 java spring reactive spring-webflux

目前我在使用新的 Spring 5 WebClient 时遇到了问题,我需要一些帮助来解决它。 问题是:

I request some url that returns json response with content type text/html;charset=utf-8.

But unfortunately I’m still getting an exception: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/html;charset=utf-8' not supported. So I can’t convert response to DTO.

对于请求,我使用以下代码:

Flux<SomeDTO> response = WebClient.create("https://someUrl")
                .get()
                .uri("/someUri").accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToFlux(SomeDTO.class);

response.subscribe(System.out::println);

顺便说一句,我在接受 header 中指向哪种类型并不重要,总是返回 text/html。那么我怎样才能最终转换我的回复呢?

最佳答案

正如前面的答案中提到的,您可以使用exchangeStrategies方法,

示例:

            Flux<SomeDTO> response = WebClient.builder()
                .baseUrl(url)
                .exchangeStrategies(ExchangeStrategies.builder().codecs(this::acceptedCodecs).build())
                .build()
                .get()
                .uri(builder.toUriString(), 1L)
                .retrieve()
                .bodyToFlux( // .. business logic


private void acceptedCodecs(ClientCodecConfigurer clientCodecConfigurer) {
    clientCodecConfigurer.customCodecs().encoder(new Jackson2JsonEncoder(new ObjectMapper(), TEXT_HTML));
    clientCodecConfigurer.customCodecs().decoder(new Jackson2JsonDecoder(new ObjectMapper(), TEXT_HTML));
}

关于java - 带有文本/html 响应的响应式(Reactive) WebClient GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553242/

相关文章:

spring - Spring 5 WebFlux 中 @Controller 和 RouterFunction 的区别

java - URI 中的非法字符

带有 Java 8 CompletableFuture 的 Spring TransactionInterceptor

java - 向 MQ 发送消息时如何删除默认的 Spring JMS 模板 header ?

java - 如何在Spring中设置多个配置文件的默认实现?

java - 我可以使用 Spring Integration 通过 RabbitMQ 进行同步/阻塞调用吗?

Spring WebFlux WebSocket 路径变量

java - Spring WebFlux Reactor - 更新 Flux 中的对象

java - 自定义组件

java - 如何在Elastic Search中按降序显示时间序列值?