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

如何在Java中解码Gzip编码的移动应用API响应数据?

如何在Java中解码gzip压缩的API请求数据

从你提供的请求头里的Content-Encoding: gzip就能确定,捕获到的postData.text是经过gzip压缩后的二进制字节流直接转为字符串导致的乱码。要还原出实际的JSON数据,只需要把乱码字符串还原为原始字节,再通过gzip解压即可,具体方案如下:

核心步骤说明

  1. 还原原始压缩字节:gzip压缩后的内容是二进制数据,直接转字符串时如果用了UTF-8这类多字节编码会损坏原始字节,所以必须用ISO-8859-1编码(单字节编码,能无损还原每个原始字节)。
  2. gzip解压得到原始数据:用Java自带的GZIPInputStream读取压缩字节流,解压后再转为UTF-8字符串(对应请求头里的charset=utf-8),就能拿到真实的JSON内容。

Java代码实现示例

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class GzipDataDecoder {
    public static String decodeCompressedGzipText(String compressedText) throws IOException {
        // 第一步:将乱码字符串还原为gzip压缩的原始字节数组
        byte[] compressedBytes = compressedText.getBytes("ISO-8859-1");
        
        // 第二步:使用GZIPInputStream解压字节流
        try (ByteArrayInputStream byteIn = new ByteArrayInputStream(compressedBytes);
             GZIPInputStream gzipIn = new GZIPInputStream(byteIn);
             ByteArrayOutputStream byteOut = new ByteArrayOutputStream()) {
            
            byte[] buffer = new byte[1024];
            int readBytes;
            while ((readBytes = gzipIn.read(buffer)) != -1) {
                byteOut.write(buffer, 0, readBytes);
            }
            
            // 第三步:将解压后的字节转为UTF-8格式的JSON字符串
            return byteOut.toString("UTF-8");
        }
    }

    public static void main(String[] args) {
        // 替换成你捕获到的乱码text内容
        String capturedCompressedText = "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0000�V[S�8\ u0014�+����l�qx�\t-�l!M)-�^�#�'�6��Jr2)��#��\u0002<���`�M ��������<3����\u001e��l�bɌ�$+�\u0001�yP�\\@�xb�L�RI^�@iY3� 53\\�\u0018��)�j3�0[D\u0001+���/�����渒�+��������*�N\u0016J�\rz50U }";
        
        try {
            String originalJson = decodeCompressedGzipText(capturedCompressedText);
            System.out.println("解压后得到的原始JSON数据:");
            System.out.println(originalJson);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("解压失败,请检查捕获的数据是否完整、是否为有效的gzip压缩内容");
        }
    }
}

注意事项

  • 要确保捕获到的text内容没有被截断,不完整的压缩数据会导致解压时抛出IOException。
  • 一定要对应请求头里的字符编码(这里是UTF-8)来转换解压后的字节,避免JSON出现乱码。

内容的提问来源于stack exchange,提问作者Maninder Jeet Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:06:28