编程语言
首页 > 编程语言> > java – GZIPInputStream到String

java – GZIPInputStream到String

作者:互联网

首先,如果我的术语有点业余,我很抱歉,试着忍受我;)

我试图将HTTP响应的gzipped主体转换为明文.我已经采用了这个响应的字节数组并将其转换为ByteArrayInputStream.然后我将其转换为GZIPInputStream.我现在想要读取GZIPInputStream并将最终解压缩的HTTP响应主体存储为纯文本字符串.

此代码将最终解压缩的内容存储在OutputStream中,但我想将内容存储为String:

public static int sChunk = 8192;
ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
byte[] buffer = new byte[sChunk];
int length;
while ((length = gzis.read(buffer, 0, sChunk)) != -1) {
        out.write(buffer, 0, length);
}

解决方法:

要从InputStream解码字节,可以使用InputStreamReader.然后,BufferedReader将允许您逐行读取流.

您的代码将如下所示:

ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);

String readed;
while ((readed = in.readLine()) != null) {
    System.out.println(readed);
}

标签:gzipinputstream,java,http,gzip
来源: https://codeday.me/bug/20191003/1851353.html