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

Unirest调用Spring Boot接口未返回Content-Encoding: gzip响应头问题

问题与解决

问题详情

我用Unirest(3.14.5版本)调用启用了gzip压缩的Spring Boot 3.3.5 API,服务器配置如下:

server.compression.enabled=true
server.compression.mime-types=application/json
server.compression.min-response-size=1

调用代码:

HttpResponse<String> response = Unirest.post(url)
                .header("Accept-Encoding", "gzip")
                .header("Content-Type", "application/json")
                .body(request)
                .asString();

服务器确实收到了Accept-Encoding: gzip请求头,但Unirest返回的响应里始终看不到Content-Encoding: gzip头,用curl或Insomnia测试却一切正常。

根因

Unirest默认会自动对gzip压缩的响应做解压缩处理,在把响应转成字符串返回给你之前,就已经完成了解压,同时会自动移除Content-Encoding头——因为此时返回的内容已经是明文,这个头的意义已经不存在了。

解决办法

办法1:关闭自动解压缩

通过Unirest的全局配置禁用自动解压缩,这样就能保留Content-Encoding头,不过之后需要自己处理内容解压:

// 全局配置关闭自动解压缩
Unirest.config().automaticDecompression(false);

// 正常发起请求
HttpResponse<String> response = Unirest.post(url)
                .header("Accept-Encoding", "gzip")
                .header("Content-Type", "application/json")
                .body(request)
                .asString();

// 现在能拿到Content-Encoding头了
String contentEncoding = response.getHeaders().getFirst("Content-Encoding");
// 需要自己处理gzip内容的解压,比如用GZIPInputStream读取响应体

办法2:获取原始响应

如果只是想查看响应头,不需要处理解压后的内容,可以用asRaw()方法获取原始响应,这样所有响应头都会被保留:

HttpResponse<RawResponse> rawResponse = Unirest.post(url)
                .header("Accept-Encoding", "gzip")
                .header("Content-Type", "application/json")
                .body(request)
                .asRaw();

// 直接读取Content-Encoding头
String contentEncoding = rawResponse.getHeaders().getFirst("Content-Encoding");
// 原始的压缩内容在rawResponse.getBody()里,是InputStream类型

内容的提问来源于stack exchange,提问作者tav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 07:32:05