java爬虫之使用HttpClient模拟浏览器发送请求方法详解
时间:2021-05-13 08:13:52|栏目:JAVA代码|点击: 次
0. 摘要
0.1 添加依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
0.2 代码
//1. 打开浏览器 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2. 输入网址
HttpGet httpGet = new HttpGet("http://www.baidu.com");
//3. 发送请求
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
//4. 响应结果
HttpEntity httpEntity = httpResponse.getEntity();
//5. 解析结果
String result = EntityUtils.toString(httpEntity, "utf-8");
System.out.println(result);
1. 实操
1.1 添加依赖
1.1.1 找到 pom.xml 添加依赖

1.1.2 依赖代码
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
1.2 添加 TestHttpClient 类
1.2.1 创建类文件 com.aifu.TestHttpClient

1.2.2 添加代码

public static void main(String[] args) throws IOException {
//1. 打开浏览器 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2. 输入网址
HttpGet httpGet = new HttpGet("http://www.baidu.com");
//3. 发送请求
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
//4. 响应结果
HttpEntity httpEntity = httpResponse.getEntity();
//5. 解析结果
String result = EntityUtils.toString(httpEntity, "utf-8");
System.out.println(result);
}
1.3 运行
1.3.1 点击绿标运行 或者快捷键 ctrl + alt +F10



阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




