HttpClient抓取网页内容简单介绍

下面说的都是HttpClient3.1版本的时候,然后再说HttpClient 4 版本

1、GET方式

第一步、创建一个客户端,类似于你用浏览器打开一个网页

HttpClient httpClient = new HttpClient();

第二步、创建一个GET方法,用来获取到你需要抓取的网页URL

GetMethod getMethod = new GetMethod("http://www.baidu.com");

第三步、获得网址的响应状态码,200表示请求成功

int statusCode = httpClient.executeMethod(getMethod);

第四步、获取网页的源码

byte[] responseBody = getMethod.getResponseBody();

主要就这四步,当然还有其他很多东西,比如网页编码的问题

[java]  view plain  copy
 print ?
  1. HttpClient httpClient = new HttpClient();  
  2.        GetMethod getMethod = new GetMethod("http://www.baidu.com/");  
  3.        try {  
  4.            int statusCode = httpClient.executeMethod(getMethod);  
  5.            if (statusCode != HttpStatus.SC_OK) {  
  6.                System.err.println("Method failed: "  
  7.                        + getMethod.getStatusLine());  
  8.            }  
  9.            // 读取内容  
  10.            byte[] responseBody = getMethod.getResponseBody();  
  11.            // 处理内容  
  12.      String html = new String(responseBody);  
  13.      System.out.println(html);   
  14.        } catch (Exception e) {  
  15.            System.err.println("页面无法访问");  
  16.        }finally{  
  17.         getMethod.releaseConnection();  
  18.     }  
2、Post方式

[java]  view plain  copy
 print ?
  1. HttpClient httpClient = new HttpClient();  
  2.        PostMethod postMethod = new PostMethod(UrlPath);  
  3.        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());  
  4.        NameValuePair[] postData = new NameValuePair[2];  
  5.        postData[0] = new NameValuePair("username""xkey");  
  6.        postData[1] = new NameValuePair("userpass""********");  
  7.        postMethod.setRequestBody(postData);  
  8.        try {  
  9.            int statusCode = httpClient.executeMethod(postMethod);  
  10.            if (statusCode == HttpStatus.SC_OK) {  
  11.                byte[] responseBody = postMethod.getResponseBody();  
  12.                String html = new String(responseBody);  
  13.                System.out.println(html);  
  14.            }  
  15.        } catch (Exception e) {  
  16.            System.err.println("页面无法访问");  
  17.        }finally{  
  18.         postMethod.releaseConnection();  
  19.     }  

这个例子传递了两个Post参数:username为xkey,userpass为********,传递给网址UrlPath

如果需要了解获取gzip网页的信息可以参考http://www.cnblogs.com/modou/articles/1325569.html

另外就是获取非字符数据,这样可以使用下面的方法

[java]  view plain  copy
 print ?
  1. HttpClient httpClient = new HttpClient();  
  2.        GetMethod getMethod = new GetMethod("http://www.baidu.com");  
  3.        try {  
  4.            InputStream inputStream = getMethod.getResponseBodyAsStream();  
  5.            // 这里处理 inputStream  
  6.        } catch (Exception e) {  
  7.            System.err.println("页面无法访问");  
  8.        }finally{  
  9.         getMethod.releaseConnection();  
  10.     }  


HttpClient4.0(摘录)

[java]  view plain  copy
 print ?
  1. class HttpClientTest {  
  2.   
  3. public final static void main(String[] args) throws Exception {  
  4.   
  5.        // 初始化,此处构造函数就与3.1中不同  
  6.        HttpClient httpclient = new DefaultHttpClient();  
  7.   
  8.        HttpHost targetHost = new HttpHost("www.google.cn");  
  9.        HttpGet httpget = new HttpGet("/");  
  10.   
  11.        // 查看默认request头部信息  
  12.        System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset"));  
  13.        // 以下这条如果不加会发现无论你设置Accept-Charset为gbk还是utf-8,他都会默认返回gb2312(本例针对google.cn来说)  
  14.        httpget.setHeader("User-Agent""Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");  
  15.        // 用逗号分隔显示可以同时接受多种编码  
  16.        httpget.setHeader("Accept-Language""zh-cn,zh;q=0.5");  
  17.        httpget.setHeader("Accept-Charset""GB2312,utf-8;q=0.7,*;q=0.7");  
  18.        // 验证头部信息设置生效  
  19.        System.out.println("Accept-Charset:" + httpget.getFirstHeader("Accept-Charset").getValue());  
  20.   
  21.        // Execute HTTP request  
  22.        System.out.println("executing request " + httpget.getURI());  
  23.         
  24.       HttpResponse response = httpclient.execute(targetHost, httpget);  
  25.        //HttpResponse response = httpclient.execute(httpget);  
  26.   
  27.        System.out.println("----------------------------------------");  
  28.        System.out.println("Location: " + response.getLastHeader("Location"));  
  29.        System.out.println(response.getStatusLine().getStatusCode());  
  30.        System.out.println(response.getLastHeader("Content-Type"));  
  31.        System.out.println(response.getLastHeader("Content-Length"));  
  32.         
  33.        System.out.println("----------------------------------------");  
  34.   
  35.        // 判断页面返回状态判断是否进行转向抓取新链接  
  36.        int statusCode = response.getStatusLine().getStatusCode();  
  37.        if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||  
  38.             (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||  
  39.             (statusCode == HttpStatus.SC_SEE_OTHER) ||  
  40.             (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {  
  41.          // 此处重定向处理   此处还未验证  
  42.          String newUri = response.getLastHeader("Location").getValue();  
  43.          httpclient = new DefaultHttpClient();  
  44.          httpget = new HttpGet(newUri);  
  45.          response = httpclient.execute(httpget);  
  46.        }  
  47.   
  48.        // Get hold of the response entity  
  49.        HttpEntity entity = response.getEntity();  
  50.         
  51.        // 查看所有返回头部信息  
  52.        Header headers[] = response.getAllHeaders();  
  53.        int ii = 0;  
  54.        while (ii < headers.length) {  
  55.          System.out.println(headers[ii].getName() + ": " + headers[ii].getValue());  
  56.          ++ii;  
  57.        }  
  58.         
  59.        // If the response does not enclose an entity, there is no need  
  60.        // to bother about connection release  
  61.        if (entity != null) {  
  62.          // 将源码流保存在一个byte数组当中,因为可能需要两次用到该流,  
  63.           byte[] bytes = EntityUtils.toByteArray(entity);  
  64.          String charSet = "";  
  65.            
  66.          // 如果头部Content-Type中包含了编码信息,那么我们可以直接在此处获取  
  67.           charSet = EntityUtils.getContentCharSet(entity);  
  68.   
  69.          System.out.println("In header: " + charSet);  
  70.          // 如果头部中没有,那么我们需要 查看页面源码,这个方法虽然不能说完全正确,因为有些粗糙的网页编码者没有在页面中写头部编码信息  
  71.          if (charSet == "") {  
  72.             regEx="(?=<meta).*?(?<=charset=[\\'|\\\"]?)([[a-z]|[A-Z]|[0-9]|-]*)";  
  73.             p=Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);  
  74.             m=p.matcher(new String(bytes));   // 默认编码转成字符串,因为我们的匹配中无中文,所以串中可能的乱码对我们没有影响  
  75.             result=m.find();  
  76.             if (m.groupCount() == 1) {  
  77.                    charSet = m.group(1);  
  78.             } else {  
  79.                    charSet = "";  
  80.             }  
  81.          }  
  82.          System.out.println("Last get: " + charSet);  
  83.          // 至此,我们可以将原byte数组按照正常编码专成字符串输出(如果找到了编码的话)  
  84.          System.out.println("Encoding string is: " + new String(bytes, charSet));  
  85.        }  
  86.   
  87.        httpclient.getConnectionManager().shutdown();         
  88. }  
  89.   
  90. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值