java爬虫返回页面乱码问题

来源:互联网 发布:软件询价函 编辑:程序博客网 时间:2024/05/29 17:59

本人  最近接触了爬虫程序,开始写了几个程序爬取国内某网站数据,期间出现了乱码问题,但总是能在设置head消息中的encoding 解决问题,今天在爬取国外网站的时候,出现了一件头疼的问题:该程序爬取回来的全部是英文数据,不管怎么设置,但总是出现乱码,研究了几个小时(本人小白一枚) 终于明白了一点问题,并解决之:

现贴上代码:

本例采用get方式  post 方式类似,请参考    抓取网站:http://fids.changiairport.com

private String getHtml(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = null;
        HttpEntity entity = null;
        HttpGet httget = null;
        try {
            HttpParams params = httpclient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, 30000);
            HttpConnectionParams.setSoTimeout(params, 60000);
            httget = new HttpGet(url);
            response = httpclient.execute(httget);
            entity = response.getEntity();
            System.out.println(entity.getContentEncoding());//此时可以打印出问题所在  输出:Content-Encoding: gzip

           /**

          *百度了一下gizp:

         *GZIP最早由Jean-loup Gailly和Mark Adler创建,用于UNⅨ系统的文件压缩。我们在Linux中经常会用到后缀为.gz的文件,它们就是GZIP格式的。现今已经成为Internet     上       使用非常普遍的一种数据压缩格式,或者说一种文件格式。  HTTP协议上的GZIP编码是一种用来改进WEB应用程序性能的技术。大流量的WEB站点常常使用GZIP压      缩技术来让用户感受更快的速度。这一般是指WWW服务器中安装的一个功能,当有人来访问这个服务器中的网站时,服务器中的这个功能就将网页内容压缩后传输到来       访的电脑浏览器中显示出来.一般对纯文本内容可压缩到原大小的40%.这样传输就快了,效果就是你点击网址后会很快的显示出来.当然这也会增加服务器的负载. 一般服务       器中都安装有这个功能模块的.

         所以我们要对返回的流进行解压 :解压代码见绿色部分

           **/
            InputStream in = entity.getContent();    //猜测 一般(非Gzip)的乱码问题  可以先打开浏览器访问网站,查看编码,在此行,用该编码降返回的流读出来即可
            return ZipUtils.uncompressToString(in, "UTF-8");
        } catch (Exception e1) {
            logger.error(FuncStatic.errorTrace(e1));
        } finally {
            if (entity != null) {
                try {
                    EntityUtils.consume(entity);
                    entity = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            httget.abort();
            httget = null;
            httpclient.getConnectionManager().shutdown();
            httpclient = null;
        }
        return null;
    }

public ZipUtils class{

 /**
     * 网页Gzip数据解压
     */
    public static String uncompressToString(InputStream in,String charset) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(charset);
        } catch (IOException e) {
                e.printStackTrace();
        }
            return null;
        }
 

}

老鸟勿喷,请友情指导,欢迎讨论