java爬虫(一) - HttpClient

40 篇文章 0 订阅
6 篇文章 0 订阅

在这里插入图片描述

📫 作者简介:「子非我鱼」,专注于研究全栈
🔥 三连支持:欢迎 ❤️关注、👍点赞、👉收藏三连,支持一下博主~

引言

网络爬虫也叫网络机器人, 是一种可以按照一定规则自动采集互联网信息的程序或脚本, 爬虫一般分为数据采集, 处理, 储存三个部分, 从若干初始网页的URL开始抓取网页, 不断获取页面上的URL放入队列直到满足系统的一定条件停止

为什么要学习爬虫
  1. 可以实现私人的搜索引擎

  2. 大数据时代获取数据源, 作数据分析

  3. 可以更好地进行搜索引擎优化 (SEO)

  4. 有利于就业, 爬虫工程师需求量大, 发展空间广

示例演示httpClient方式

导入所需依赖

		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
普通 get 方式
		// 创建httpclients对象,可以理解为打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 输入网址 发送get请求
        HttpGet get = new HttpGet("http://www.myqxin.com");
        // 发送并接收响应结果
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            // 解析响应,获取数据
            if (response.getStatusLine().getStatusCode() == 200) {
                // 响应体数据
                HttpEntity entity = response.getEntity();
                String conut = EntityUtils.toString(entity, "utf8");
                System.out.println(conut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
带参 get 方式
		// 创建httpclients对象,可以理解为打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            URIBuilder uriBuilder = null;
            uriBuilder = new URIBuilder("http://www.myqxin.com");
            // 设置参数
            uriBuilder.setParameter("username", "myqxin");
            // 输入网址 发送get请求
            HttpGet get = new HttpGet(uriBuilder.build());
            // 发送并接收响应结果
            response = httpClient.execute(get);
            // 解析响应,获取数据
            if (response.getStatusLine().getStatusCode() == 200) {
                // 响应体数据
                HttpEntity entity = response.getEntity();
                String conut = EntityUtils.toString(entity, "utf8");
                System.out.println(conut);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
             	// 关闭连接
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
普通 post 方式
		// 创建httpclients对象,可以理解为打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 输入网址 发送get请求
        HttpPost get = new HttpPost("http://www.myqxin.com");
        // 发送并接收响应结果
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            // 解析响应,获取数据
            if (response.getStatusLine().getStatusCode() == 200) {
                // 响应体数据
                HttpEntity entity = response.getEntity();
                String conut = EntityUtils.toString(entity, "utf8");
                System.out.println(conut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
带参 post 方式
		// 创建httpclients对象,可以理解为打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 输入网址 发送post请求
        HttpPost post = new HttpPost("http://www.myqxin.com");
        // 声明list集合,封装表单参数
        ArrayList<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("username", "myqxin"));
        params.add(new BasicNameValuePair("password", "1234"));
        CloseableHttpResponse response = null;
        try {
            // 创建表单的entity对象,第一个参数就是封装表单数据,第二个参数就是编码
            UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(params, "utf8");
            // 设置表单的entity对象到post请求中
            post.setEntity(entity1);
            // 发送并接收响应结果
            response = httpClient.execute(post);
            // 解析响应,获取数据
            if (response.getStatusLine().getStatusCode() == 200) {
                // 响应体数据
                HttpEntity entity = response.getEntity();
                String conut = EntityUtils.toString(entity, "utf8");
                System.out.println(conut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
创建连接池管理httpClient

当频繁创建销毁httpClient,这时候就需要通过连接池来管理httpClient

public static void main(String[] args) {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager pm = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        pm.setMaxTotal(100);
        // 设置每个主机的最大连接数
        pm.setDefaultMaxPerRoute(10);
        // 使用连接池管理器发送请求
        doGet(pm);
        doGet(pm);
    }

  public static void doGet(PoolingHttpClientConnectionManager pm) {
        // 获取连接池的 httpclient
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(pm).build();
        // 输入网址 发送get请求
        HttpGet get = new HttpGet("http://www.myqxin.com");
        // 发送并接收响应结果
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(get);
            // 解析响应,获取数据
            if (response.getStatusLine().getStatusCode() == 200) {
                // 响应体数据
                HttpEntity entity = response.getEntity();
                String conut = EntityUtils.toString(entity, "utf8");
                System.out.println(conut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
关于httpClient请求参数

有时候因为网络,或者目标服务器的原因,请求需要更长的时间才能完成,我们需要自定义相关时间

// 创建httpclients对象,可以理解为打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 输入网址 发送get请求
        HttpGet get = new HttpGet("http://www.myqxin.com");
        // 配置请求信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)   // 创建连接的最长时间,单位:毫秒
                .setConnectionRequestTimeout(500)   // 获取连接的最长时间,单位:毫秒
                .setSocketTimeout(10*1000)  // 设置数据传输的最长时间,单位:毫秒
                .build();
        // 给请求设置请求信息
        get.setConfig(config);
        // 发送并接收响应结果
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            // 解析响应,获取数据
            if (response.getStatusLine().getStatusCode() == 200) {
                // 响应体数据
                HttpEntity entity = response.getEntity();
                String conut = EntityUtils.toString(entity, "utf8");
                System.out.println(conut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子非我鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值