手拉手Java爬虫HttpClient

JAVA爬虫

HttpClient

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

使用 HttpClient 的 6 个步骤
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,选择get或post请求
3. 确定是否有参数
4. 执行请求,并获得 response响应,然后获得HttpEntity对象
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理

Pom.xml添加依赖

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>

GET请求

不带参

public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet对象,设置url
HttpGet httpGet =new HttpGet("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
System.out.println("发起请求信息:"+httpGet);

CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpGet);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

带参

public static void main(String[] args) throws Exception {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置带参的url地址http://yun.itheima.com/search?keys=java
URIBuilder uriBuilder =new URIBuilder("http://yun.itheima.com/search");
uriBuilder.setParameter("keys","java");

//创建HttpGet对象,设置url
HttpGet httpGet =new HttpGet(uriBuilder.build());
System.out.println("发起请求信息:"+httpGet);

CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpGet);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

POST请求

不带参

public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost对象,设置url
HttpPost httpPost = new HttpPost("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
System.out.println("发起请求信息:"+httpPost);

CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpPost);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}


 

带参

public static void main(String[] args) throws UnsupportedEncodingException {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost对象,设置url
HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
System.out.println("发起请求信息:"+httpPost);
//声明list集合,封装表单中的参数
List<NameValuePair> params =new ArrayList<NameValuePair>();
//设置带参的url地址http://yun.itheima.com/search?keys=java
params.add(new BasicNameValuePair("keys","java"));
//创建表单的Entity对象
UrlEncodedFormEntity formEntity =new UrlEncodedFormEntity(params,"utf8");
//设置表单的Entity对象到Post请求中
httpPost.setEntity(formEntity);


CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpPost);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

连接池

public static void main(String[] args) {
PoolingHttpClientConnectionManager cm =new PoolingHttpClientConnectionManager();
//设置连接数
cm.setMaxTotal(100);
//设置没个主机的最大连接数
cm.setDefaultMaxPerRoute(10);

doGet(cm);
}

private static void doGet(PoolingHttpClientConnectionManager cm) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
HttpGet httpGet =new HttpGet("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
CloseableHttpResponse response =null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content.length());
}

}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

连接请求配置

配置请求信息
//setConnectTimeout创建连接的最长时间,毫秒 、setConnectionRequestTimeout获取连接的最长

时间,毫秒
RequestConfig config =RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).build();

httpGet.setConfig(config);

Jsoup解析

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

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

maven加入依赖

<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>

Jsoup解析Url

@Test
public void JUrl()throws Exception{
//解析url地址,参数1:要访问的url,参数2:访问超时时间
Document doc = Jsoup.parse(new URL("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#zh/en/"), 100000);
//使用标签选择器
String text = doc.getElementsByTag("title").first().text();
System.out.println(text);
}

Jsoup解析文件

//解析文件
 

Document doc = Jsoup.parse(new File("F:\\front\\code\\vue01\\比较数字大小.html"),"utf8");
String text = doc.getElementsByTag("title").first().text();
System.out.println(text);

Dom方式获取元素

元素获取

1.根据d查询元素 getElementByld

2.根据标签获取元素 getElementsByTag

3.根据 class i获取元素 getElementsByClass

4.根据属性获取元素 getElementsByAttribute

@Test
public void DOMGet()throws Exception{
//解析文件
Document doc = Jsoup.parse(new File("F:\\front\\code\\vue01\\dom与diff算法.html"),"utf8");
//1.根据d查询元素 getElementById
Element elementById = doc.getElementById("101");
System.out.println("获取到文件内容:"+elementById.text());
//2.根据标签获取元素 getElementsByTag
Element th = doc.getElementsByTag("th").first();
System.out.println("获取到文件内容:"+th.text());
//3.根据 class i获取元素 getElementsByClass
Elements abc = doc.getElementsByClass("abc");
System.out.println("获取到文件内容:"+abc.text());
//4.根据属性获取元素 getElementsByAttribute
Elements id = doc.getElementsByAttribute("id");
System.out.println(id.text());
Elements id1 = doc.getElementsByAttributeValue("id", "101");
System.out.println(id1.text());
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/479920.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

环信新版单群聊UIKit集成指南——Android篇

前言 环信新版UIKit已重磅发布&#xff01;目前包含单群聊UIKit、聊天室ChatroomUIKit&#xff0c;本文详细讲解Android端单群聊UIKit的集成教程。 环信单群聊 UIKit 是基于环信即时通讯云 IM SDK 开发的一款即时通讯 UI 组件库&#xff0c;提供各种组件实现会话列表、聊天界…

【国家计算机二级C语言】高分笔记

二叉树 参考 http://t.csdnimg.cn/ozVwT 数据库 SQL程序语言有四种类型&#xff0c;对数据库的基本操作都属于这四类&#xff0c;它们分别为&#xff1b;数据定义语言(DDL)、数据查询语言&#xff08;DQL&#xff09;、数据操纵语言&#xff08;DML&#xff09;、数据控制语言…

Day17:LeedCode 110.平衡二叉树 257.二叉树的所有路径 404.左叶子之和

110. 平衡二叉树 给定一个二叉树&#xff0c;判断它是否是 平衡二叉树 平衡二叉树:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 思路: 二叉树节点的深度&#xff1a;指从根节点到该节点的最长简单路径边的条数。二叉树节点的高度&#xff1a;指从该节点到叶…

深度探索:在 Postman 中实现自动化测试的全面指南!

在当今的软件开发过程中&#xff0c;API&#xff08;应用程序编程接口&#xff09;的使用变得越来越普遍&#xff0c;API 允许不同系统之间进行通信和数据交换&#xff0c;从而实现复杂的功能和服务集成&#xff0c;为了确保 API 的可靠性和稳定性&#xff0c;自动化测试至关重…

如何利用RunnerGo简化性能测试流程

在软件开发过程中&#xff0c;测试是一个重要的环节&#xff0c;需要投入大量时间和精力来确保应用程序或网站的质量和稳定性。但是&#xff0c;随着应用程序变得更加复杂和庞大&#xff0c;传统的测试工具在面对比较繁琐的项目时非常费时费力。这时&#xff0c;一些自动化测试…

量子计算+运营优化!IonQ 和 德国DESY 合作提升机场登机口调度效率

内容来源&#xff1a;量子前哨&#xff08;ID&#xff1a;Qforepost&#xff09; 编辑丨慕一 编译/排版丨 沛贤 深度好文&#xff1a;1200字丨8分钟阅读 3月14日&#xff0c;量子计算公司IonQ宣布了与德国电子同步加速器&#xff08;DESY&#xff0c;德国的大型粒子物理学研…

出现nginx error 问题

报错&#xff1a; Something has triggered an error on your website. This is the default error page for nginx that is distributed with Fedora. It is located /usr/share/nginx/html/50x.html You should customize this error page for your own site or edit the er…

PLC网关在工业自动化领域的作用及如何选择-天拓四方

一、PLC网关在工业自动化领域的重要性和作用 PLC网关在工业自动化领域的重要性和作用不言而喻。作为工业自动化系统的重要组成部分&#xff0c;PLC网关起到了关键的桥梁作用&#xff0c;实现了PLC与其他设备、系统之间的数据传输和通信。 首先&#xff0c;PLC网关的重要性体现…

nodeJs 学习

常用快捷键 二、fs模块 回调函数为空&#xff0c;则表示写入成功&#xff01; 练习 const fs require(fs); fs.readFile(../files/成绩.txt, utf-8, (err, dataStr) > {if (err) {console.log(读取失败);return err;}console.log(读取成功);const arr dataStr.split( )co…

SpringBoot整合WebService

WebService是一个SOA&#xff08;面向服务的编程&#xff09;的架构&#xff0c;它是不依赖于语言&#xff0c;不依赖于平台&#xff0c;可以实现不同的语言间的相互调用&#xff0c;通过Internet进行基于Http协议的网络应用间的交互。 其实WebService并不是什么神秘的东西&…

MISC:常见编码

一、字符编码 1.ASCII码 使用指定7位或8位二进制数组合表示128-256种可能。 常⻅考点&#xff1a;解题过程中给出十进制或十六进制的连续数值。 进制转换工具&#xff1a; ASCII text,Hex,Binary,Decimal,Base64 converter (rapidtables.com) 2.Base64编码 ASCII编码以8个比特…

鸿蒙Harmony应用开发—ArkTS(@Prop装饰器:父子单向同步)

Prop装饰的变量可以和父组件建立单向的同步关系。Prop装饰的变量是可变的&#xff0c;但是变化不会同步回其父组件。 说明&#xff1a; 从API version 9开始&#xff0c;该装饰器支持在ArkTS卡片中使用。 概述 Prop装饰的变量和父组件建立单向的同步关系&#xff1a; Prop变量…

马斯克的 Grok-1 开源,3140亿参数目前最大开源模型,最佳实践教程来啦

近几天开源社区最大的热点&#xff0c;莫过于埃隆马斯克信守承诺的最大开源模型Grok-1。 Grok-1 是一款 314B 大型专家混合 (Mixture of Expert&#xff0c;MoE) Transformer&#xff0c;作为基础模型&#xff0c;基于大量文本数据进行训练&#xff0c;没有针对任何具体任务进…

计算机二级Python题目3

题目来源&#xff1a;计算机二级Python半个月抱佛脚大法&#xff08;内呈上真题版&#xff09; - 知乎 目录 1. 基础题 1.1 基础题1 1.2 基础题2 1.3 基础题3 2. turtle绘图题 3. 大题 3.1 大题1 3.2 大题2 1. 基础题 1.1 基础题1 a,b,ceval(input()) ls[] for i in …

Base系列

1.计数系统 base,这个词在数学中表示基数&#xff0c;即计数系统中用于表示数字的不同符号的数量。 例&#xff1a; 二进制计数系统中只有两个符号表示数字&#xff0c;即0和1&#xff0c;故二进制系统可以用Base2表示。 十进制计数系统中仅使用十个符号表示数字&#xff0c;即…

二、阅读器的开发(初始)-- 2、阅读器开发

1、epubjs核心工作原理 1.1 epubjs的核心工作原理解析 epub电子书&#xff0c;会通过epubjs去实例化一个Book对象&#xff0c;Book对象会对电子书进行解析。Book对象可以通过renderTo方法去生成一个Rendition对象&#xff0c;Rendition主要负责电子书的渲染&#xff0c;通过R…

QT gridlayout 循环设置组件,表格也通用 已解决

在需求中。经常遇到&#xff0c;表格 展示需求。 几乎都是json格式的。 // 列表配置文件QJsonArray listJsonArray getCfgJsonData("details_tab_table_config.json");if (listJsonArray.isEmpty()){return;}ui->gridWidget->setMaximumSize(QSize(310, 180)…

Matlab在高光谱遥感中的作用:从数据处理到决策支持

光谱和图像是人们观察世界的两种方式&#xff0c;高光谱遥感通过“图谱合一”的技术创新将两者结合起来&#xff0c;大大提高了人们对客观世界的认知能力&#xff0c;本来在宽波段遥感中不可探测的物质&#xff0c;在高光谱遥感中能被探测。以高光谱遥感为核心&#xff0c;构建…

【机器学习300问】44、P-R曲线是如何权衡精确率和召回率的?

关于精确率和召回率的基础概念我已经写了两篇文章&#xff0c;如果友友还不知道这两个评估指标是什么&#xff0c;可以先移步去看看这两篇文章&#xff1a; 【机器学习300问】25、常见的模型评估指标有哪些&#xff1f;http://t.csdnimg.cn/JtuUO 总结一下这两个概念&a…

进度图画法

exce表格进度图画法&#xff0c;体现在条形图以及“格子”的空间的填充两种办法。 1.excel表格画进度图 备注&#xff1a;表格照着就是可以了&#xff0c;主要是画直线的办法 在形状的下拉菜单中选择直线&#xff0c;按住shift&#xff08;可以画直线&#xff09; 画直线后&a…
最新文章