You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.5中RestClient发起POST请求返回响应内容乱码/编码异常问题排查

Spring Boot 3.5中RestClient发起POST请求返回响应内容乱码/编码异常问题排查

我仔细看了你的代码和调试日志,很快就定位到了问题核心——你的RestClient没有处理gzip压缩的响应!

从日志里的响应头能明确看到:

content-encoding:"gzip"

这说明API返回的是经过gzip压缩的JSON数据,但你的RestClient完全没配置自动解压逻辑,所以直接拿到了压缩后的二进制字节流,打印出来自然就是那些乱码字符。而Postman默认会自动处理gzip压缩,所以你在Postman里能正常看到结果。

下面给你具体的解决步骤:

1. 修复无效的请求头配置

你原来代码里的this.restClient.head().accept(MediaType.APPLICATION_JSON);这行完全没用!head()方法是用来构建HEAD请求的,根本不会设置RestClient的默认请求头。你需要改用defaultHeader来配置全局默认请求头,同时加上Accept-Encoding告诉服务器你支持gzip压缩。

2. 配置RestClient支持gzip解压

推荐使用Apache HttpClient作为请求工厂,它能自动处理gzip解压。首先在pom.xml里添加依赖:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
</dependency>

然后修改你的RestClient构建代码:

public VivxWebApiService(RestClient.Builder restClientBuilder, ApplicationLocationConfiguration applicationLocationConfiguration) {
    List<HttpMessageConverter<?>> vivxHttpMessageConverters = new ArrayList<>();
    vivxHttpMessageConverters.add(new FormHttpMessageConverter());
    vivxHttpMessageConverters.add(new MappingJackson2HttpMessageConverter());

    // 配置支持自动解压gzip的请求工厂
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setContentCompressionEnabled(true)
                    .build())
            .build());

    this.restClient = restClientBuilder
            .baseUrl(applicationLocationConfiguration.getVivxWebApi())
            .messageConverters(vivxHttpMessageConverters)
            .requestFactory(requestFactory)
            // 设置默认请求头,告诉服务器你支持JSON和gzip压缩
            .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            .defaultHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate")
            .build();
}

3. 验证修改效果

修改完成后,RestClient会自动发送Accept-Encoding: gzip, deflate请求头,收到gzip压缩的响应时会自动解压,之后MappingJackson2HttpMessageConverter就能正常将解压后的JSON数据转换成你的VivxDesignColorDataResponse对象了。

当然你也可以不用Apache HttpClient,自己实现请求拦截器来处理解压,但用HttpClient的方式更简单可靠,也是Spring官方推荐的方案之一。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:48:06