网络爬虫入门系列(3) httpClient
? ? 上一篇文章介紹了? Jsoup設置請求頭, 抓取網頁的java 代碼?
? ? 這一篇文章介紹 httpClient 設置請求頭 抓取網頁的? java 代碼實現
? ? 首先? 到官網 上 下載 httpClient? ?這里下載的 是? 4.5.5版本的?
? ?http://mirror.bit.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5.5-bin.zip
? ? 將
commons-logging-1.2.jar
httpclient-4.5.5.jar
httpcore-4.4.9.jar
httpmime-4.5.5.jar
? ?導入到項目中 ,
? ?新建一個類 ,?httpClientConnection
? ? ?編寫如下代碼?
? ? ? ??
public class httpClientConnection {
public static void main(String[] args) {
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse responseGet = null;
try {
// 以get方法執行請求
HttpGet httpGet = new HttpGet("http://www.cnblogs.com/szw-blog/p/8565944.html");
// 獲得服務器響應的所有信息
responseGet = httpclient.execute(httpGet);
System.out.println(responseGet.getStatusLine());
// 獲得服務器響應的消息體(不包括http head)
HttpEntity entity = responseGet.getEntity();
if (entity != null) {
// 獲得響應字符集編碼
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
InputStream is = entity.getContent();
// 將inputstream轉化為reader,并使用緩沖讀取,還可按行讀取內容
BufferedReader br = new BufferedReader(
new InputStreamReader(is, charset));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
responseGet.close();
httpclient.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
responseGet.close();
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
運行后的結果是?
?
?
?
以上就是 java 使用httpclient 抓取網頁的? 簡單代碼
?
轉載于:https://www.cnblogs.com/szw-blog/p/8569925.html
總結
以上是生活随笔為你收集整理的网络爬虫入门系列(3) httpClient的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鸡蛋的做法大全家常?
- 下一篇: 吃烧烤时如何配上美味的烤串?