I am attempting to convert the gzipped body of a HTTP response to plaintext. I've taken the byte array of this response and converted it to a ByteArrayInputStream. I've then converted this to a GZIPInputStream. I now want to read the GZIPInputStream and store the final decompressed HTTP response body as a plaintext String.
This code will store the final decompressed contents in an OutputStream, but I want to store the contents as a 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);
}
To decode bytes from an InputStream, you can use an InputStreamReader. Then, a BufferedReader will allow you to read your stream line by line.
Your code will look like:
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);
}