---
title: "判断是否为GZIPInputStream格式（gzip压缩格式）"
author: "wingware"
date: "2012-08-03T18:15:30Z"
tags: []
categories: ["编程语言"]
slug: "gzipinputstream-gzip"
draft: false
lastmod: "2012-08-03T18:16:42Z"
id: 1618561
url: "https://wingware.iteye.com/blog/1618561"
---

```java
                InputStream ips = null;
		// 取前两个字节
		byte[] header = new byte[2];
		if (isGzip()) {
			try {
				BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
				bis.mark(2);
				int result = bis.read(header);
				// reset输入流到开始位置
				bis.reset();
				// 判断是否是GZIP格式
				int ss = (header[0] & 0xff) | ((header[1] & 0xff) << 8);
				if(result!=-1 && ss == GZIPInputStream.GZIP_MAGIC) {
					//System.out.println("为数据压缩格式...");
					ips= new GZIPInputStream(bis);
				} else {
			        // 取前两个字节
					ips= bis;
				}
			} catch (java.io.IOException e) {
				e.printStackTrace();
				ips = connection.getInputStream();
			}
		} else {
			ips = connection.getInputStream();
		}
```


判断header中是否包含有gzip

```java
public boolean isGzip() {
		boolean gzip = false;
		for (String key : this.getHeaders().keySet()) {
			if (key.equalsIgnoreCase("Accept-Encoding") && this.getHeaders().get(key).contains("gzip")) {
				gzip = true;
				break;
			}
		}
		return gzip;
	}
```