java - 如何覆盖任何 HttpHeader 以响应 WebClient?

标签 java spring webclient spring-webflux spring-webclient

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/

相关文章:

java - Spring Boot - 如何在一个地方记录所有带有异常的请求和响应?

java - spring Autowiring 与资源

c# - 通过 REST 在列表中插入项目

http - Powershell System.Net.WebClient 认证

java - 为什么事务在 Spring JPA 中没有回滚到所需的传播级别?

java - 未使用资源的 Android Lint 警告不正确

java - 如何使用Spring Batch连接服务器?

c# - 使用 WebClient 异步下载文件不起作用

Java - 使舞台不对用户交互使用react

java - 使用多线程递增/递减/打印(代码审查)