手拉手Java爬虫HttpClient

news2024/9/30 17:33:22

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.coloradmin.cn/o/1537666.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深度学习新篇章:PyTorch在遥感地物分类的革命性应用

我国高分辨率对地观测系统重大专项已全面启动&#xff0c;高空间、高光谱、高时间分辨率和宽地面覆盖于一体的全球天空地一体化立体对地观测网逐步形成&#xff0c;将成为保障国家安全的基础性和战略性资源。未来10年全球每天获取的观测数据将超过10PB&#xff0c;遥感大数据时…

四种最新算法(小龙虾优化算法COA、螳螂搜索算法MSA、红尾鹰算法RTH、霸王龙优化算法TROA)求解机器人路径规划(提供MATLAB代码)

一、机器人路径规划介绍 移动机器人&#xff08;Mobile robot&#xff0c;MR&#xff09;的路径规划是 移动机器人研究的重要分支之&#xff0c;是对其进行控制的基础。根据环境信息的已知程度不同&#xff0c;路径规划分为基于环境信息已知的全局路径规划和基于环境信息未知或…

Simulink无法求解/代数环/数值问题/求解器不收敛

运行仿真时出错&#xff0c;仿真终止 原因: Simulink cannot solve the algebraic loop containing Gain at time 1.0000000000000142 due to one of the following reasons: the model is ill-defined i.e., the system equations do not have a solution; or the nonlinear …

Linux:文件读取指令

Linux&#xff1a;文件读取指令 cat指令more指令less指令head指令 & tail指令grep指令 cat指令 cat指令用于查看目标文件的内容。 语法&#xff1a;cat [选项][文件] 比如直接使用cat读取一个文件&#xff1a; 可以看到&#xff0c;其直接在指令的下方&#xff0c;输出了t…

嵌入式开发--STM32G431RBTx-产生PWM

嵌入式开发–STM32G431RBTx-产生pwm 定时器工作原理 如图有反映stm32g431的定时器资源。 共10个定时器 定时器定时器类型个数TIM6&#xff0c;7基本定时器2TIM2&#xff0c;3&#xff0c;4全功能通用定时器3TIM15&#xff0c;16&#xff0c;17通用定时器(只有1或2个通道)3TI…

计算机二级大题

题目来源&#xff1a;计算机二级Python半个月抱佛脚大法&#xff08;内呈上真题版&#xff09; - 知乎 1.大题1 注意csv文件读取的处理 ls[] for line in f: ls.append(line.strip(\n).split(,)) 2. 大题2 第一问&#xff1a; #计算有效票张数 fopen("vote.txt",…

普发Pfeiffer分子泵TMH-U1001PC-1601PC安装使用维护说明

普发Pfeiffer分子泵TMH-U1001PC-1601PC安装使用维护说明

【十七】【算法分析与设计】前缀和(2)

238. 除自身以外数组的乘积 给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#…

碳素光线疗法——动,植物 光育实验

碳素光线疗法——动&#xff0c;植物 光育实验 碳素光线疗法&#xff1a; 中西医、民间疗法融为一体&#xff0c;提高机体自身治愈力&#xff0c;免疫力&#xff0c;改善体质和保持健康&#xff0c;有助于疾病的预防和治疗的疗法。不吃药、不打针、不手术也能得健康&#xff0c…

【Grass Mining】教程

Grass 为用户提供了一种利用网络资源进行Mining的新途径。以下是一份简化的指南&#xff0c;帮助您轻松开始在 Grass 上的Mining活动。 开始之前&#xff1a;注册 Grass 账户 首先&#xff0c;访问 Grass 官方网站进行账户注册。如果遇到注册过程中出现的“失败”提示&#x…

Android Jetpack:简化开发、提高Android App质量的利器

Android Jetpack&#xff1a;简化开发、提高Android App质量的利器 1. Jetpack的概念和目标 Jetpack是一套库、工具和指南&#xff0c;旨在帮助开发者更轻松地编写高质量的应用程序。这些组件帮助开发者遵循最佳实践&#xff0c;减少样板代码的编写&#xff0c;并简化复杂的任…

2024年,抖音小店无货源怎么做?一篇全解!

大家好&#xff0c;我是电商糖果 无货源不能做了&#xff1f; 以后是不是要商家自己进货&#xff0c;囤货了&#xff1f; 无货源未来还有发展前景吗&#xff1f; ....... 这些问题&#xff0c;从2022年就有不少朋友开始问&#xff0c;一直到2024年。 糖果做无货源电商已经…

训练YOLOv9-S

1. YOLOv9-S网络结构 1.1 改前改后的网络结构&#xff08;参数量、计算量&#xff09;对比 修改前调用的yolo.py测试的yolov9.yaml的打印网络情况&#xff0c;包含参数量、计算量 修改后调用的yolo.py测试的yolov9.yaml的打印网络情况&#xff0c;包含参数量、计算量 1.2 …

MySQL关联查询如何优化

好久不见&#xff0c;关于这篇文章&#xff0c;我也是想了很久&#xff0c;还是决定写一篇文章&#xff0c;有很多同学问过 mysql 相关的问题&#xff0c;其实关联查询如何优化&#xff0c;首先我们要知道关联查询的原理是什么&#xff1f; 左连接 left join SELECT 字段列表…

单目测距那些事儿(上) _ 从MobileEye谈起

单目测距那些事儿(上) | 从MobileEye谈起 全面专业的自动驾驶学习资料:链接 前言 在ADAS领域&#xff0c;有个功能叫自适应巡航控制(Adaptive Cruise Control, ACC)。 ACC是一种纵向距离控制&#xff0c;具体包括发现目标车辆、判断目标车辆所在路径、测量相对本车的距离和速…

STM32之HAL开发——手动移植HAL库

HAL库移植步骤 创建目录 配置启动文件 在\Drivers\CMSIS\Device\ST\stm32f1xx\Source\Templates\ARM目录下&#xff0c;根据你的芯片型号选择对应的启动文件&#xff0c;不同容量大小的芯片&#xff0c;对应的启动文件也不一样。 注意&#xff1a;在HAL库中&#xff0c;不同容…

离散型工业生产制造MES管理系统解决方案

一、核心优势 1、业务场景高适配 ①配置好程度高,可适应不同的业务场景。 ②业务功能灵活可配,可根据客户需求及时调整。 2、功能覆盖全周期 产品功能覆盖面广,能够实现从来料管理到销售出库整个产品生命周期管控。 3、触点互联降成本 能将相关的设备集成至MES中来,实现与设…

全网最靠谱的短网址平台,你知道几个?

在当今互联网时代&#xff0c;短网址平台成为了人们分享链接的常用工具。它们不仅可以将冗长的网址压缩为简洁的短链接&#xff0c;还能提供更多的功能和优势。在众多的短网址平台中&#xff0c;有几个平台以其可靠性和出色的性能脱颖而出。今天&#xff0c;我们就来介绍几个全…

跳槽多次未成功,问题源自何处?

众所周知&#xff0c;2023年市场很难&#xff01;看着企业们纷纷裁员&#xff0c;甚至连内推这个后门都走不通&#xff01;哪怕有面试&#xff0c;都是屡屡碰壁&#xff0c;你想清楚问题出在哪了吗&#xff1f;&#x1f62d;“求职不得&#xff0c;夜不能寐&#xff1b;三更半夜…

设计模式—观察者模式与发布订阅

观察者设计模式 观察者设计模式&#xff08;Observer Design Pattern&#xff09;是一种常用的软件设计模式&#xff0c;它是一种行为型模式。该模式用于定义对象之间的一种一对多的依赖关系&#xff0c;当一个对象的状态发生改变时&#xff0c;所有依赖于它的对象都将得到通知…