使用GET与POST方式获取html数据

抓取网站数据解析的工作,其中,使用到GET和POST方法获取html数据。

使用GET方式:

[java]
  1. /** 
  2.  * 使用get方式获取html数据 
  3.  *  
  4.  * @param strURL(需要访问的网站) 
  5.  * @return 
  6.  * @throws Exception 
  7.  */  
  8. public String getHTML(String strURL) throws Exception {  
  9.     //创建浏览器  
  10.     HttpClient httpClient = HttpClients.createDefault();  
  11.     String html = null;  
  12.     //预防网址链接中包含特殊字符,将url转为uri  
  13.     URL url = new URL(strURL);  
  14.     URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),  
  15.             url.getQuery(), null);  
  16.     //使用get方式  
  17.     HttpGet request = new HttpGet(uri);  
  18.     HttpResponse response;  
  19.     try {  
  20.         //连接网址获取返回的数据  
  21.         response = httpClient.execute(request);  
  22.         //将返回的数据按照gbk的方式编码  
  23.         html = EntityUtils.toString(response.getEntity(), "GBK");  
  24.     } catch (IOException e) {  
  25.         e.printStackTrace();  
  26.     }  
  27.     //断开连接  
  28.     request.abort();  
  29.     //返回网址所发挥的html数据  
  30.     return html;  
  31. }  

使用该方法便可以获取得到网站所发挥的html数据。

使用POST方式:

[java]
  1. /** 
  2.      * 使用post方式获取html数据 
  3.      *  
  4.      * @param libraryUrl(需要访问的网站) 
  5.      * @param params(需要传入的参数) 
  6.      * @return 
  7.      * @throws Exception 
  8.      */  
  9.     public String postHTML(String strURL, List<NameValuePair> params)  
  10.             throws Exception {  
  11.         //创建浏览器  
  12.         HttpClient httpClient = HttpClients.createDefault();  
  13.         String html = null;  
  14.         //预防网址链接中包含特殊字符,将url转为uri  
  15.         URL url = new URL(strURL);  
  16.         URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),  
  17.                 url.getQuery(), null);  
  18.         //使用POST方式  
  19.         HttpPost request = new HttpPost(uri);  
  20.         //将参数封装进UrlEncodedFormEntity中  
  21.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);  
  22.         request.setEntity(entity);  
  23.         HttpResponse response;  
  24.         try {  
  25.             //连接网址获取返回的数据  
  26.             response = httpClient.execute(request);  
  27.             //将返回的数据按照gbk的方式编码  
  28.             html = EntityUtils.toString(response.getEntity(), "GBK");  
  29.         } catch (IOException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         //断开连接  
  33.         request.abort();  
  34.         //返回网址所发挥的html数据  
  35.         return html;  
  36.     }  

其中,参数params的封装可以参照以下方式:

[java]
  1. List<NameValuePair> params = new ArrayList<NameValuePair>();  
  2. //以键值对的方式存储  
  3. params.add(new BasicNameValuePair("format", "hitcount"));  
原文地址:https://www.cnblogs.com/appcx/p/6963229.html