解压缩 Gzip JSON 响应:StreamCorruptedException:无效流 header:7B227061

Decompressing Gzip JSON Response : StreamCorruptedException: invalid stream header: 7B227061

所以基本上我试图通过解压缩 gzip 来获得 gzip 编码的 json 对 java 中的 pojo 的响应。起初我从 api 调用中得到字节数组形式的响应。

CategoriesFullDetails categoriesFullDetails = new CategoriesFullDetails();
        UriComponents getAllCategoriesUri = UriComponentsBuilder
                .fromHttpUrl(baseUrl + MENU_CATEGORY_FULL)
                .buildAndExpand(businessId);
        String getAllCategoriesUrl = getAllCategoriesUri.toUriString();
        HttpHeaders requestHeaders = new HttpHeaders();

        requestHeaders.set("Content-Type", "application/json");
        requestHeaders.set("Accept-Encoding", "gzip");

        HttpEntity httpEntity = new HttpEntity(requestHeaders);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        client.setRequestFactory(requestFactory);
        client.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        byte[] responseBytes = client
                .exchange(getAllCategoriesUrl, HttpMethod.GET, httpEntity, byte[].class).getBody();

如上所示,一旦我将 gzip 响应转换并存储为字节数组,我想将其解压缩并将其添加到我的一个 pojo,即 CategoriesFullDetails。

下面我调用解压缩字节数组的方法。

            try {
                categoriesFullDetails = decompress(responseBytes);
                return categoriesFullDetails;
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
                return  null;
            }

    public CategoriesFullDetails decompress(byte[] data) throws IOException, ClassNotFoundException {
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        GZIPInputStream gis = new GZIPInputStream(in);
        ObjectInputStream is = new ObjectInputStream(gis);
        return (CategoriesFullDetails) is.readObject();
    }

因此,我在调试此解压缩方法时发现,它将数据转换为 ByteArrayInputStream,然后成功转换为 GZIPInputStream(该方法的前两行工作正常)。但是随后在 ObjectInputStream is = new ObjectInputStream(gis); 抛出错误 说 StreamCorruptedException: 无效流 header: 7B227061

我希望有人能帮助我解决这个问题,已经三天了,我仍然无法解决。

7B227061 是此 ASCII 的十六进制等价物:

{"pa

即它看起来像 JSON 数据的前 4 个字节。问题是你有一个 gzip 压缩的 JSON 文本流,你将它传递给一个 ObjectInputStream,它用于读取序列化的 Java 对象数据。

只需将 GzipObjectStream 传递给您的 JSON 解析器。或者,如果您愿意,将整个输入流读入一个字符串,然后将该字符串传递给您的解析器。

例如,如果您使用的是 Jackson,则:

ObjectMapper mapper = new ObjectMapper();
CategoriesFullDetails jsonMap = mapper.readValue(gis, CategoriesFullDetails.class);