• 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

  • 相关阅读:
    HttpClient request payload post请求
    【Linux】svn添加用户
    手机抓包fiddle4的安装及配置
    【论文笔记】Social Role-Aware Emotion Contagion in Image Social Networks
    【Linux】crontab 定时启动sh
    DIV+CSS网页设计规范
    【机器学习】粗糙集属性约简算法与mRMR算法的本质区别
    【机器学习】DBSCAN Algorithms基于密度的聚类算法
    【机器学习】EM的算法
    【机器学习】K-means聚类算法与EM算法
  • 原文地址:https://www.cnblogs.com/yxth/p/11232174.html
Copyright © 2020-2023  润新知