溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

好程序員Java教程分享使用HttpClient抓取頁面內(nèi)容

發(fā)布時間:2020-07-12 18:52:45 來源:網(wǎng)絡(luò) 閱讀:192 作者:wx5da18b5c4b01e 欄目:編程語言

好程序員Java教程分享使用HttpClient抓取頁面內(nèi)容,使用HttpClient工具來發(fā)送Http請求

1.簡介
HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。HttpClient 已經(jīng)應(yīng)用在很多的項目中,比如 Apache Jakarta 上很著名的另外兩個開源項目 Cactus 和 HTMLUnit 都使用了 HttpClient。

HttpClient 相比傳統(tǒng) JDK 自帶的 URLConnection,增加了易用性和靈活性,它不僅是客戶端發(fā)送 HTTP 請求變得容易,而且也方便了開發(fā)人員測試接口(基于 HTTP 協(xié)議的),即提高了開發(fā)的效率,也方便提高代碼的健壯性。因此熟練掌握 HttpClient 是很重要的必修內(nèi)容,掌握 HttpClient 后,相信對于 HTTP 協(xié)議的了解會更加深入。

2.應(yīng)用場景
點擊并拖拽以移動?
好程序員Java教程分享使用HttpClient抓取頁面內(nèi)容
3.HttpClient工具的使用
1)添加依賴
<!-- Apache Http Begin -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>
<!-- Apache Http End -->

2)編寫測試代碼@Test
br/>@Test

//1.獲得HttpClient對象

CloseableHttpClient client = HttpClients.
createDefault
();
//2.創(chuàng)建請求對象,如果是post請求 HttpPost 如果是get請求 HttpGet對象

String uri = "http://www.baidu.com";
HttpGet get = new HttpGet(uri);
//3.執(zhí)行g(shù)et請求,獲得響應(yīng)消息對象

CloseableHttpResponse response = client.execute(get);
//4.獲取響應(yīng)行

StatusLine statusLine = response.getStatusLine();
//5.獲取狀態(tài)碼

int code = statusLine.getStatusCode();
if(code==200){
//響應(yīng)成功

HttpEntity entity = response.getEntity();
//6.獲取響應(yīng)體中的內(nèi)容

// InputStream is = entity.getContent();

// byte[] b = new byte[8192];

// int len = 0;

// while((len = is.read(b))!=-1){

// System.out.println(new String(b,0,len));

// }

// is.close();

System.
out
.println(EntityUtils.
toString
(entity, "utf-8"));
}

}

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI