判断是否为GZIPInputStream格式(gzip压缩格式)
转自 http://wingware.iteye.com/blog/1618561
- 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
- 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;
- }