带有文本/html响应的反应式WebClient GET请求 [英] Reactive WebClient GET Request with text/html response
问题描述
当前,我在使用新的Spring 5 WebClient时遇到问题,需要一些帮助来进行整理. 问题是:
Currently I’m having an issue with new Spring 5 WebClient and I need some help to sort it out. The issue is:
我请求一些返回json响应的URL,其内容类型为 text/html; charset = utf-8 .
但不幸的是,我仍然遇到一个例外: org.springframework.web.reactive.function.UnsupportedMediaTypeException: 不支持内容类型'text/html; charset = utf-8'.所以我不能 将响应转换为DTO.
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.
对于请求,我使用以下代码:
For request I use following code:
Flux<SomeDTO> response = WebClient.create("https://someUrl")
.get()
.uri("/someUri").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(SomeDTO.class);
response.subscribe(System.out::println);
顺便说一句,我指向接受标头的类型并不重要,总是返回text/html.那么我怎么才能最终转换我的回答?
Btw, it really doesn’t matter which type I point in accept header, always returning text/html. So how could I get my response converted eventually?
推荐答案
让服务发送带有"text/html"
Content-Type的JSON是很不常见的.
Having a service send JSON with a "text/html"
Content-Type is rather unusual.
有两种处理方法:
- 将Jackson解码器配置为也解码
"text/html"
内容;查看WebClient.builder().exchangeStrategies(ExchangeStrategies)
设置方法 - 动态更改"Content-Type"响应标头
- configure the Jackson decoder to decode
"text/html"
content as well; look into theWebClient.builder().exchangeStrategies(ExchangeStrategies)
setup method - change the "Content-Type" response header on the fly
以下是第二种解决方案的建议:
Here's a proposal for the second solution:
WebClient client = WebClient.builder().filter((request, next) -> next.exchange(request)
.map(response -> {
MyClientHttpResponseDecorator decorated = new
MyClientHttpResponseDecorator(response);
return decorated;
})).build();
class MyClientHttpResponseDecorator extends ClientHttpResponseDecorator {
private final HttpHeaders httpHeaders;
public MyClientHttpResponseDecorator(ClientHttpResponse delegate) {
super(delegate);
this.httpHeaders = new HttpHeaders(this.getDelegate().getHeaders());
// mutate the content-type header when necessary
}
@Override
public HttpHeaders getHeaders() {
return this.httpHeaders;
}
}
请注意,您仅应在该上下文中(对于此主机)使用该客户端. 如果可以的话,我强烈建议您尝试修复服务器返回的那种奇怪的内容类型.
Note that you should only use that client in that context (for this host). I'd strongly suggest to try and fix that strange content-type returned by the server, if you can.
这篇关于带有文本/html响应的反应式WebClient GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!