项目去文件服务器下载图片,发现部分图片下载下来无法预览,用浏览器去下载又能成功,最后抓包发现下载图片时,http头部指定了
非压缩文件,但是服务器依然返回了 压缩文件。
最后解决方法,下载完成后,判断是否是压缩文件,是的话,解压缩
public static void handleGzipFile(State state, Response response) throws Throwable {
String mimeType = response.header("Content-Type");
if (!TextUtils.isEmpty(mimeType)) {
mimeType = sanitizeMimeType(mimeType);
if (mimeType.startsWith("image/")) {
String encoding = response.header("Content-Encoding");// 验证一下是否GZip压缩
if (!TextUtils.isEmpty(encoding) && "gzip".equals(encoding)) {
File ttf = new File(state.mFilename);
File decodeFile = decodeGZipFile(ttf);
ttf.delete();
// 重命名之前,对临时文件,做一次图片校验,用BitmapFactory解析一下
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(decodeFile.getAbsolutePath(), opts);
// 如果解析的宽高度小于1,默认为非图片
if (opts.outWidth < 1 && opts.outHeight < 1) {
throw new Throwable("is not a image");
}
if (!decodeFile.renameTo(new File(state.mFilename))) {
throw new Throwable("rename fail!");
}
}
}
}
}
public static File decodeGZipFile(File file) throws IOException {
GZIPInputStream gzipIn = null;
FileOutputStream gzipOut = null;
try {
gzipIn = new GZIPInputStream(new FileInputStream(file));
file = new File(file.getAbsolutePath() + ".gziptemp");
gzipOut = new FileOutputStream(file);
byte[] buf = new byte[1024 * 8];
int num = -1;
while ((num = gzipIn.read(buf, 0, buf.length)) != -1) {
gzipOut.write(buf, 0, num);
}
} finally {
if (gzipIn != null)
gzipIn.close();
if (gzipOut != null)
gzipOut.close();
}
return file;
}