首页 > 解决方案 > 如何覆盖任何 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

标签: javaspringwebclientspring-webfluxspring-webclient

解决方案


我有类似的问题,接受的答案对我不起作用。我这样做是为了覆盖我收到的无效内容类型。

/**
     * 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()));
    }

推荐阅读