有没有办法检查InputStream是否已经被gzip压缩过了?以下是代码:
public static InputStream decompressStream(InputStream input) {
try {
GZIPInputStream gs = new GZIPInputStream(input);
return gs;
} catch (IOException e) {
logger.info("Input stream not in the GZIP format, using standard format");
return input;
}
}
我尝试过这种方法,但它并没有像预期的那样工作-从流中读取的值无效。 编辑: 添加了我用于压缩数据的方法:
public static byte[] compress(byte[] content) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
GZIPOutputStream gs = new GZIPOutputStream(baos);
gs.write(content);
gs.close();
} catch (IOException e) {
logger.error("Fatal error occured while compressing data");
throw new RuntimeException(e);
}
double ratio = (1.0f * content.length / baos.size());
if (ratio > 1) {
logger.info("Compression ratio equals " + ratio);
return baos.toByteArray();
}
logger.info("Compression not needed");
return content;
}
InputStream
是从哪里来的?是从URLConnection#getInputStream()
来的吗?在像 HTTP 这样稍微正式的协议中,最终用户应该已经以某种方式被告知内容是经过 gzip 压缩的。 - BalusC