目前我在使用新的 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/