I am experiencing the following IOException when using the GZIPInputStream:
java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:131)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:58)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:68)
...
I am trying to read an Entity Body from an HTTP response that has been compressed using GZIP compression. I read in chunks of 4K bytes, but my first read always ends at the Entity Body (this is not a problem of course, but I thought it was a bit odd). However, this my first read of an InputStream always gives me the following:
Status-Line
Headers
CRLF
So, the next read would return me the first byte of the Entity Body. By investigating the supplied Headers I discovered that GZIP compression is used. Therefore, I create a GZIPInputStream with the original InputStream as parameter. But when I start reading from the GZIPInputStream I get the mentioned exception.
Looking into the GZIPInputStream it seems to have a problem with the GZIP header magic number (0x8b1f). This magic number consists of two bytes. I thought it would be nice to try the following, just to see what happend:
...
byte[] gzipHeader = new byte[2];
inputStream.read(gzipHeader, 0, gzipHeader.length);
GZIPInputStream gzipInputStream =
new GZIPInputStream(
new SequenceInputStream(
new ByteArrayInputStream(gzipHeader), inputStream));
...
And guess what? This seems to solve my problem, however I would not consider this to be a nice fix. Looking to see what is in the byte array, I discovered the following: 0x1f8b. I found the following snippet of code in GZIPInputStream:
private int readUShort(InputStream in) throws IOException {
int b = readUByte(in);
return ((int)readUByte(in) << 8) | b;
}
This method is used to read in the GZIP header magic number. Now correct me if I'm wrong, but reading the bytes 0x1f8b results in the desired 0x8b1f. Therefore my little test mentioned earlier works, but why doesn't the following work:
...
GZipInputStream gzipInputStream = new GZIPInputStream(inputStream);
....
Can anybody help me with this?
Jack...