標籤: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方式爬取網頁,簡易類操作。