java - 如何覆盖任何 HttpHeader 以响应 WebClient?
问题描述
WebClient.builder().baseUrl("/").filter(contentTypeInterceptor()).build();
如何修改Content-Type
收到的响应(因为我收到来自发出错误内容类型的网络服务器的响应。由于我无法控制外部服务器,我想进一步更正内容类型正确处理(例如使用杰克逊库等)。
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
解决方案
我有类似的问题,接受的答案对我不起作用。我这样做是为了覆盖我收到的无效内容类型。
/**
* 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()));
}
推荐阅读
- vb.net - 如何在 vb.net 中的 if else 条件循环中获得总计数?
- python - 动态创建嵌套的for循环
- kotlin-exposed - 如何在 Kotlin Exposed 的一对多关系中设置级联类型?
- java - 在 doFilter 调用后设置响应标头
- video - 如何添加没有自动循环和自动播放的媒体播放器的视频
- android - 标记上的弹出窗口(InfoBubble)单击此处地图
- themes - 使用 React Context 时如何修复此错误
- javascript - 在单击事件中,从不同级别向每个 HTML 元素添加类,
- mysql - 如何将 Intellij 中运行的 Spark 作业连接到本地 mysql hive 元存储?
- wordpress - url设置错误后无法打开wordpress面板