网络爬虫-java-1

一、相关知识介绍

1、HttpClient:HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

2、如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。

3、Jsoup:jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。

4、jsoup的主要功能:1)从一个URL,文件或字符串中解析HTML;2)使用DOM或CSS选择器来查找、取出数据;3)可操作HTML元素、属性、文本;

二、测试代码

1、maven项目的依赖

<dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
<!--            <scope>test</scope>-->
        </dependency>
    </dependencies>
View Code

2、使用HttpClient连接池管理HttpClient,使用get、post的方式做两次简单的请求

package com.me.study;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class Study1 {
    private static PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
    public static void main(String[] args)  {
        //    设置最大连接数
        pool.setMaxTotal(200);
        //    设置每个主机的并发数
        pool.setDefaultMaxPerRoute(20);
        Study1 study1 = new Study1();
        study1.httpGet();
        study1.httpPost();
    }

    private void httpPost()  {
            //使用连接池管理HttpClient
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pool).build();
            //创建HttpGet请求
            HttpPost httpPost = new HttpPost("https://www.bookben.net/");
            //设置请求参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(1000)//设置创建连接的最长时间1s
                    .setConnectionRequestTimeout(500)//设置获取连接的最长时间0.5s
                    .setSocketTimeout(10 * 1000)//设置数据传输的最长时间10s
                    .build();

            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            try {
                //使用HttpClient发起请求
                response = httpClient.execute(httpPost);
                //判断响应状态码是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    //如果为200表示请求成功,获取返回数据
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    //打印数据长度
                    System.out.println(content);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放连接
                if (response == null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

    }

    public void httpGet()  {
        //使用连接池管理HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pool).build();
        //创建HttpGet请求 = 输入网址
        HttpGet httpGet = new org.apache.http.client.methods.HttpGet("https://www.bookben.net/");
        //设置请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)//设置创建连接的最长时间
                .setConnectionRequestTimeout(500)//设置获取连接的最长时间
                .setSocketTimeout(10 * 1000)//设置数据传输的最长时间
                .build();

        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            //使用HttpClient发起请求 获取响应 response
            response = httpClient.execute(httpGet);
            //判断响应状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                //如果为200表示请求成功,获取返回数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //打印数据长度
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (response == null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
View Code

猜你喜欢

转载自www.cnblogs.com/20183544-wangzhengshuai/p/12461637.html