Decompress GZip string in Java

Mat*_*att 14 java gzip

I can find plenty of functions that let you decompress a GZip file, but how do I decompress a GZip string?

I'm trying to parse a HTTP response where the response body is compressed with GZip. However, the entire response is simply stored in a string so part of the string contains binary chars.

I'm attempting to use:

byte responseBodyBytes[] = responseBody.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(responseBodyBytes); 
GZIPInputStream gzis = new GZIPInputStream(bais);
Run Code Online (Sandbox Code Playgroud)

But that just throws an exception: java.io.IOException: Not in GZIP format

Jon*_*eet 15

没有GZip字符串这样的东西.GZip是二进制的,字符串是文本.

如果要压缩字符串,则需要先将其转换为二进制 - 例如,OutputStreamWriter链接到压缩OutputStream(例如a GZIPOutputStream)

同样,为了读取数据,您可以使用InputStreamReader链接到解压缩InputStream(例如a GZIPInputStream).

从一个易于阅读的一种方法Reader是使用CharStreams.toString(Readable)番石榴,或类似的库.