WebClient.builder().baseUrl("/").filter(contentTypeInterceptor()).build();
如何修改收到的响应的Content-Type
(因为我从发出错误内容类型的 Web 服务器收到响应。由于我无法控制外部服务器,因此我想更正内容类型以进行进一步的正确处理(例如杰克逊库等(。
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 标头。
就我而言,根本原因是我收到了text/html
,但响应正文实际上是一个application/xml
。jackson
拒绝解析该响应,原因如下:
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/html' not supported for bodyType=MyResponse
艾哈迈德的回答在技术上是正确的。但是,我相信在我发布本文时,该ClientResponse.from()
已被弃用,您应该使用 .mutate()
方法来创建新的生成器。
private ExchangeFilterFunction contentTypeInterceptor() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse ->
Mono.just(clientResponse.mutate()
.headers(headers -> headers.remove(HttpHeaders.CONTENT_TYPE))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build()));
}
我有类似的问题,接受的答案对我不起作用。我这样做是为了覆盖我收到的无效内容类型。
/**
* 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()));
}
也许是这样的?
private ExchangeFilterFunction contentTypeInterceptor() {
return ExchangeFilterFunction.ofRequestProcessor(clientRequest ->
Mono.just(ClientRequest.from(clientRequest)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
.build()));
}