2
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

4

3 回答 3

4

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

/**
     * 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()));
    }
于 2020-03-01T12:42:30.313 回答
2

艾哈迈德的回应在技术上是正确的。但是,我相信在我发布此内容时,它ClientResponse.from()已被弃用,您应该使用该.mutate()方法创建一个新的 Builder。

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()));
}
于 2021-03-19T11:58:52.230 回答
1

也许是这样的?

private ExchangeFilterFunction contentTypeInterceptor() {
    return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> 
        Mono.just(ClientRequest.from(clientRequest)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)
            .build()));
}
于 2019-07-09T13:35:39.833 回答