有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

基本上,我试图通过解压gzip来获得对java中pojo的gzip编码json响应。首先,我从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:无效流头:7B227061

我希望有人能帮我解决这个问题,已经三天了,但我还是解决不了


共 (1) 个答案

  1. # 1 楼答案

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

    {"pa
    

    也就是说,它看起来像JSON数据的前4个字节。问题是,您有一个JSON文本的gzip流,并且将其传递给ObjectInputStream,后者用于读取序列化的Java对象数据

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

    例如,如果你正在使用Jackson,那么:

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