WebClient.builder().baseUrl("/").filter(contentTypeInterceptor()).build();
如何修改收到的响应的 Content-Type
(因为我收到来自发出错误内容类型的网络服务器的响应。因为我无法控制外部服务器,我想更正内容类型以进一步正确处理(例如使用 jackson 库等)。
private ExchangeFilterFunction contentTypeInterceptor() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
org.springframework.web.reactive.function.client.ClientResponse.Headers headers = clientResponse.headers();
//TODO how to headers.setContentType("myval) or headers.set("Content-Type", "myval");
//headers.asHttpHeaders(); cannot be used as it is readonly
});
}
这个问题可以一般地回答如何覆盖任何http header 。
在我的例子中,根本原因是我收到了 text/html
,但响应正文实际上是 application/xml
。并且 jackson
拒绝解析该响应,原因是:
org.springframework.web.reactive.function.UnsupportedMediaTypeException:bodyType=MyResponse 不支持内容类型“text/html”
最佳答案
我遇到了类似的问题,并且接受的答案对我不起作用。 我这样做是为了覆盖我收到的无效内容类型。
/**
* webclient interceptor that overrides the response headers ...
* */
private ExchangeFilterFunction contentTypeInterceptor() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse ->
Mono.just(
ClientResponse
.from(clientResponse) //clientResponse is immutable, so,we create a clone. but from() only clones headers and status code
.headers(headers -> headers.remove(HttpHeaders.CONTENT_TYPE)) //override the content type
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
.body(clientResponse.body(BodyExtractors.toDataBuffers()) ) // copy the body as bytes with no processing
.build()));
}
关于java - 如何覆盖任何 HttpHeader 以响应 WebClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56950034/