Java爬虫的实现

距离上一次写爬虫还是几年前了,那时候一直使用的是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();

 

 

 

 

 

Processor

posted @ 2019-07-23 15:41  一响贪欢  阅读(1407)  评论(0编辑  收藏  举报