java response 获得code_Java教程分享使用HttpClient抓取页面内容
Java教程分享使用HttpClient抓取頁(yè)面內(nèi)容,使用HttpClient工具來(lái)發(fā)送Http請(qǐng)求
1.簡(jiǎn)介
HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。HttpClient 已經(jīng)應(yīng)用在很多的項(xiàng)目中,比如 Apache Jakarta 上很著名的另外兩個(gè)開(kāi)源項(xiàng)目 Cactus 和 HTMLUnit 都使用了 HttpClient。
HttpClient 相比傳統(tǒng) JDK 自帶的 URLConnection,增加了易用性和靈活性,它不僅是客戶端發(fā)送 HTTP 請(qǐng)求變得容易,而且也方便了開(kāi)發(fā)人員測(cè)試接口(基于 HTTP 協(xié)議的),即提高了開(kāi)發(fā)的效率,也方便提高代碼的健壯性。因此熟練掌握 HttpClient 是很重要的必修內(nèi)容,掌握 HttpClient 后,相信對(duì)于 HTTP 協(xié)議的了解會(huì)更加深入。
2.應(yīng)用場(chǎng)景
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)編寫(xiě)測(cè)試代碼
@Testpublic void testHttpClient() throws IOException {//1.獲得HttpClient對(duì)象
CloseableHttpClient client = HttpClients.createDefault();//2.創(chuàng)建請(qǐng)求對(duì)象,如果是post請(qǐng)求 HttpPost 如果是get請(qǐng)求 HttpGet對(duì)象
String uri = "baidu com";
HttpGet get = new HttpGet(uri);//3.執(zhí)行g(shù)et請(qǐng)求,獲得響應(yīng)消息對(duì)象
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"));
}
}
總結(jié)
以上是生活随笔為你收集整理的java response 获得code_Java教程分享使用HttpClient抓取页面内容的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 地下城与勇士中所有材料的用途是什么?
- 下一篇: hash的算法 java_【数据结构与算