判断是否为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;
- }
本文介绍了一种使用 Java 代码判断 HTTP 响应是否采用 GZIP 压缩的方法,并提供了相应的代码实现。通过读取响应头部的前两个字节来确定压缩格式,并检查 Accept-Encoding 头部字段是否存在 gzip 关键词。

1099

被折叠的 条评论
为什么被折叠?



