问题
So, my Java application reveives some data that is generated with PHP's gzdeflate(). Now i'm trying to inflate that data with Java. This is what i've got so far:
InflaterInputStream inflInstream = new InflaterInputStream(new ByteArrayInputStream(inputData.getBytes() ), new Inflater());
byte bytes[] = new byte[1024];
while (true) {
int length = inflInstream.read(bytes, 0, 1024);
if (length == -1) break;
System.out.write(bytes, 0, length);
}
'inputData' is a String containing the deflated data.
The problem is: the .read method throws an exception:
java.util.zip.ZipException: incorrect header check
Other websites on this subject only go as far as redirecting me to the Inflater class' documentation, but apparently I don't know how to use it to be compatible with PHP.
回答1:
Per the documentation, php gzdeflate() generates raw deflate data (RFC 1951), but Java's Inflater class is expecting zlib (RFC 1950) data, which is raw deflate data wrapped in zlib header and trailer. Unless you specify nowrap as true to the Inflater constructor. Then it will decode raw deflate data.
InputStream inflInstream = new InflaterInputStream(new ByteArrayInputStream(inputData.getBytes()),
new Inflater(true));
byte bytes[] = new byte[1024];
while (true) {
int length = inflInstream.read(bytes, 0, 1024);
if (length == -1) break;
System.out.write(bytes, 0, length);
}
回答2:
Use the GZIPInputStream as per examples at (do not use the Inflater directly):
http://java.sun.com/developer/technicalArticles/Programming/compression/
来源:https://stackoverflow.com/questions/11399350/gzinflate-in-java