距離上一次寫爬蟲還是幾年前了,那時候一直使用的是httpclient。
由於最近的項目又需要使用到爬蟲,因此又重新查詢了一些爬蟲相關的框架,其中最合適的是WebMagic
官方文檔:https://github.com/code4craft/webmagic
官方教程:http://webmagic.io/docs/zh/
WebMagic里面也是封裝了httpclient來進行請求。因此不論是否直接使用WebMagic框架, 都是使用到了httpclient。
PS:httpclient3和4版本區別較大,下面代碼均是在httpclient4的基礎上進行測試開發。
HttpClient
1.創建HttpClient
HttpClients.createDefault()
HttpClients.createSystem()
HttpClients.createMinimal()
HttpClients.createMinimal(HttpClientConnectionManager)
2.post請求
2.1創建一個post請求
String uri = ""; HttpPost post = new HttpPost(uri);
2.2添加請求頭
post.setHeader("Connection", "keep-alive"); post.setHeader("Accept-Encoding", "gzip, deflate"); ......
2.3添加請求參數
List<NameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("username", "test")); list.add(new BasicNameValuePair("password", "123")); post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
2.4發起請求
HttpResponse response = httpClient.execute(post);
3.get請求
3.1創建一個get請求
String uri = ""; URIBuilder uriBuilder = new URIBuilder(uri); HttpGet get = new HttpGet(uriBuilder.build());
3.2添加請求頭
get.setHeader("Connection", "keep-alive"); get.setHeader("Accept-Encoding", "gzip, deflate"); ......
3.3添加請求參數
uriBuilder.setParameter("param1", "1"); uriBuilder.setParameter("param2", "2"); ......
3.4發起請求
HttpResponse response = httpClient.execute(get);
4.響應信息
發起請求后都會獲得一個響應對象HttpResponse。
響應中主要包含了響應頭、狀態碼、響應信息。
狀態碼一般是200和302,302表示請求重定向,可以從它的響應頭中獲取重定向的新路徑,再次發起請求,如下
int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 302) { String location = response.getFirstHeader("location").getValue(); System.out.println("302 new uri : " + location);
如果發起成功,可以讀取里面的響應信息。
響應信息分為多種,如html、照片、文件、json等等。具體情況需要根據實際區分。
html、json
String content = EntityUtils.toString(response.getEntity());
照片、文件
HttpEntity entity = response.getEntity(); OutputStream os = null; os = new FileOutputStream(pdfPath + filenames.get()); InputStream is = entity.getContent(); while (true) {//這個循環讀取網絡數據,寫入本地文件 byte[] bytes = new byte[1024 * 1024]; //1M int k = is.read(bytes); if (k >= 0) { os.write(bytes, 0, k); os.flush(); } else break; } os.close(); is.close();
啊