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