使用apache httpClient 通過get方式爬取網頁,簡易類操作。

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   os   使用   sp   java   

                 

                 我是從官網下載的最新版本,windows作業系統選zip版本就行了。

                 在網上搜的一些資料,感覺提供的類有點舊了。新下載的包沒有相關類,用法也不對。對了,我下載的版本是4.3.6。


                 所以只能自己搜尋資料摸索,在下載的包中有相應的guide指導,還有一些現成的例子。


                我自己寫了一個簡單的例子:

       

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.HttpEntity;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;/** * 最簡單的HTTP用戶端,用來示範通過GET方式訪問某個頁面 *  * @author napoleonjk */public class SimpleClient {public static void main(String[] args) {String uri = "http://localhost:8080/xxxxxxxx";System.out.println(new SimpleClient().doGet(uri));}public String doGet(String uri) {String result = "";try {CloseableHttpClient httpclient = HttpClients.createDefault();// 建立HttpGet,將要請求的URL通過構造方法傳入HttpGet對象。HttpGet httpget = new HttpGet(uri);CloseableHttpResponse response = httpclient.execute(httpget);HttpEntity httpEntity = response.getEntity();InputStream inputStream = httpEntity.getContent();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));String line = "";while ((line = br.readLine()) != null) {result += "\n" + line;}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}}
注意點:1.代理問題

              一開始,想爬取百度的首頁,老是報告以下錯誤,後來發現是因為公司使用的代理,需要進行代理設定。

             java.net.UnknownHostException: www.baidu.com

             我嫌麻煩,索性訪問本地正在做的項目的地址,結果成功擷取頁面內容。

             2.多線程並發訪問,設定訪問間隔,類比登陸,資料存放區

              當你想把這個類寫的完善時,以上是你需要考慮的問題。

使用apache httpClient 通過get方式爬取網頁,簡易類操作。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.