使用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"));  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM