HttpClient抓包返回值乱码

来源:互联网 发布:软件管理系统php 编辑:程序博客网 时间:2024/05/22 15:30
       最近在使用HttpClient抓包时获取数据时,返回得到的数据一直都是乱码,刚开始以为是header头部的字符编码与后台的编码不一致导致的乱码,但是经过各种转编码后还是不行。然后仔细研究http头信息,发现这个url返回的数据是 Content-Encoding:
gzip 类型的数据,用IE浏览器请求这种链接的话得到的会是一个ZIP文件下载,返回的数据都压缩在了zip文件里面了。
所以,如果使用普通的
    InputStream in = null;    BufferedReader reader = null;    HttpEntity entity = response.getEntity();    if(entity != null){      String line;      in = entity.getContent();      reader = new BufferedReader(new InputStre  amReader(in,"UTF-8"));    }
InputStream类去读取数据,不管你如何转换编码类型,得到的都会是乱码,InputStream类本身不能解析到ZIP压缩文件。所以,改成:
    InputStream in = null;    GZIPInputStream gzip = null;    BufferedReader reader = null;    HttpEntity entity = response.getEntity();    if(entity != null){      String line;      in = entity.getContent();      gzip = new GZIPInputStream(in);      reader = new BufferedReader(new InputStre  amReader(gzip ,"UTF-8"));    }

使用GZIPInputStream类去读取ZIP文件,就不会乱码啦。

 备注:很多URL的头信息ContentType-Encoding的类型也是GZIP,但是返回的数据也不是通过压缩文件返回,用InputStream类读取返回数据就可以。具体是什么原因,
    如何辨别返回的数据类型是压缩文件还是普通的数据,这个有时间再慢慢分析了。
0 0
原创粉丝点击