如何在java中解压调用api响应?

2sbarzqh  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(309)

我要解压缩api响应(标题: Accept-encoding=gzip ).
以下是我尝试过但总是失败的几行: java.util.zip.ZipException: Not in GZIP format ```
String entity = response.readEntity(String.class);
// When I print "entity" I will get Compress message as below:
��{o�ʒ��
���c^MC��������ut4"�ms���fWGگ�_o?�V�G�ę�=�PF�3��i�������ɚ���G�[�eEA����$��M�(�rW�nk��97�m�r��6�$�$T�a^ZaIj�"�5U�4�����4:oW�C{�-��A�c0�hސ�l���JP�ƚ.������t�
}ˏ�r�kIxjk��!���m�0��Z�9 ���r[�����6!٦^fQ�X_d)hބe���m��\RP�Y��Xg�:�F�IEE�5]U��f�\jϋ�?N�ߖ�<�κ;�+��j�xQ�{����40�]4N�NOib�=o(r�mL�rLϱ�>Rۖ�l4
{2jʁk��f�
�љw��a�l���������^�V�a�ӱ���w[2�V>n��'��n���;�ȧ�#�p-ch}<>�9>�IB�~X��X���=��lz9)H��2#O?�R����*�����q�c�V�t����c�ܩ<��A��[���4
��

byte[] input = entity.getBytes();

// helper method
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
// Always failed at "GZIPInputStream" line due to java.util.zip.ZipException: Not in GZIP format
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}

x0fgdtte

x0fgdtte1#

在调用decompress()之前,您的问题在代码中,因此您应该编辑显示如何获得此流的问题。
一旦解决了,你会发现 decompress() 剥离行结束符,使生成的字符串位于一行上。这可能是无效的-取决于你正在阅读的格式。
如果需要保留utf-8编码的gzip字符串的格式,可以用stringwriter替换bufferedreader和stringbuilder,如下所示:

public static String decompress(byte[] compressed) throws IOException {
    try(GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
        InputStreamReader r = new InputStreamReader(gis, "UTF-8"))
    {
        StringWriter sb = new StringWriter(compressed.length * 3 / 2);
        r.transferTo(sb);
        return sb.toString();
    }
}

相关问题