禁止java爬虫_Java爬虫的实现

距离上一次写爬虫还是几年前了,那时候一直使用的是httpclient。

由于最近的项目又需要使用到爬虫,因此又重新查询了一些爬虫相关的框架,其中最合适的是WebMagic

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 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= newURIBuilder(uri);

HttpGetget = 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());

InputStreamis =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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值