本文簡(jiǎn)介:
用org.apache.http.client.methods下的接口或類完成爬蟲程序遂鹊。
1. 爬蟲的基本概念:
爬蟲肝集,是一種自動(dòng)獲取特定網(wǎng)頁(yè)內(nèi)容的程序抓谴。
2. 所需用到的類或接口
CloseableHttpResponse: 該接口實(shí)現(xiàn)HttpResponse接口和Closeable接口虐先。前者用于當(dāng)收到一個(gè)請(qǐng)求時(shí)怨愤,響應(yīng)一個(gè)HTTP信息;后者用于關(guān)閉資源蛹批。
CloseableHttpClient: 該抽象類實(shí)現(xiàn)HttpClient接口和Closeable借口撰洗。前者用于代表http請(qǐng)求執(zhí)行的最基本協(xié)議;后者用于關(guān)閉資源腐芍。
HttpGet: 該類繼承于HttpRequestBase類了赵。用于實(shí)現(xiàn)Get請(qǐng)求。
HttpEntity: 該接口用于創(chuàng)建一個(gè)可以在HTTP消息中被發(fā)送或被收到的實(shí)體甸赃。
EntityUtils: 是final class柿汛,有處理HttpEntitys的靜態(tài)方法。
3. 小例子
Get請(qǐng)求:
public class Test{
public static void main(String[] args) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = httpclient.execute(httpGet);
//輸出響應(yīng)頭
for(Header h: response.getAllHeaders())
System.out.println(h.getName() + ":" + h.getValue());
System.out.println("-----------------------------------------");
HttpEntity entity1 = response.getEntity();
//輸出響應(yīng)內(nèi)容
System.out.println(EntityUtils.toString(entity1));
}
}
結(jié)果:
結(jié)果.png
IDE:Eclipse
jar包下載:http://hc.apache.org/downloads.cgi