zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    windows下如何添加、删除和修改静态路由
    node.js后台快速搭建在阿里云(二)(pm2和nginx篇)
    使用PM2守护Nodejs命令行程序
    使用pm2管理nodejs应用
    ubuntu 下安装nodejs以及pm2
    nginx优化缓冲缓存
    nginx proxy_buffer_size 解决后端服务传输数据过多,其实是header过大的问题
    经济规律 宏观调控 与个体
    宏观调控
    《论教育》-------叔本华
  • 原文地址:https://www.cnblogs.com/yxth/p/11232174.html
Copyright © 2011-2022 走看看