抓取網站數據解析的工作,其中,使用到GET和POST方法獲取html數據。
使用GET方式:
- /**
- * 使用get方式獲取html數據
- *
- * @param strURL(需要訪問的網站)
- * @return
- * @throws Exception
- */
- public String getHTML(String strURL) throws Exception {
- //創建瀏覽器
- HttpClient httpClient = HttpClients.createDefault();
- String html = null;
- //預防網址鏈接中包含特殊字符,將url轉為uri
- URL url = new URL(strURL);
- URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
- url.getQuery(), null);
- //使用get方式
- HttpGet request = new HttpGet(uri);
- HttpResponse response;
- try {
- //連接網址獲取返回的數據
- response = httpClient.execute(request);
- //將返回的數據按照gbk的方式編碼
- html = EntityUtils.toString(response.getEntity(), "GBK");
- } catch (IOException e) {
- e.printStackTrace();
- }
- //斷開連接
- request.abort();
- //返回網址所發揮的html數據
- return html;
- }
使用該方法便可以獲取得到網站所發揮的html數據。
使用POST方式:
- /**
- * 使用post方式獲取html數據
- *
- * @param libraryUrl(需要訪問的網站)
- * @param params(需要傳入的參數)
- * @return
- * @throws Exception
- */
- public String postHTML(String strURL, List<NameValuePair> params)
- throws Exception {
- //創建瀏覽器
- HttpClient httpClient = HttpClients.createDefault();
- String html = null;
- //預防網址鏈接中包含特殊字符,將url轉為uri
- URL url = new URL(strURL);
- URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
- url.getQuery(), null);
- //使用POST方式
- HttpPost request = new HttpPost(uri);
- //將參數封裝進UrlEncodedFormEntity中
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
- request.setEntity(entity);
- HttpResponse response;
- try {
- //連接網址獲取返回的數據
- response = httpClient.execute(request);
- //將返回的數據按照gbk的方式編碼
- html = EntityUtils.toString(response.getEntity(), "GBK");
- } catch (IOException e) {
- e.printStackTrace();
- }
- //斷開連接
- request.abort();
- //返回網址所發揮的html數據
- return html;
- }
其中,參數params的封裝可以參照以下方式:
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //以鍵值對的方式存儲
- params.add(new BasicNameValuePair("format", "hitcount"));