上一篇
httpclient网络爬虫
- 行业动态
- 2025-04-29
- 3148
HTTPClient网络爬虫基于HTTP协议模拟浏览器请求,通过发送GET/POST请求获取网页源码,结合HTML解析技术提取数据,支持多线程爬取与Cookie管理,需处理反爬机制(如IP限制、验证码),适用于结构化数据抓取,需遵守
工具简介
HttpClient是Apache提供的HTTP协议客户端工具包,支持多种HTTP操作(如GET/POST),适用于构建网络爬虫,其优势包括:
- 灵活配置:可自定义请求头、超时时间、代理等参数
- 高效连接管理:支持连接池复用
- 多协议支持:兼容HTTP/1.1及HTTP/2
- 异常处理机制:提供详细的错误反馈
环境搭建
Maven依赖配置
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
核心类说明
类名 | 功能描述 |
---|---|
CloseableHttpClient | 可关闭的HTTP客户端 |
HttpGet | 封装GET请求 |
HttpPost | 封装POST请求 |
RequestConfig | 请求配置(超时/重定向) |
HttpResponse | 服务器响应对象 |
基础用法演示
简单GET请求
// 创建HttpClient实例 CloseableHttpClient httpClient = HttpClients.createDefault(); // 构造GET请求 HttpGet request = new HttpGet("https://www.example.com"); // 执行请求并获取响应 try (CloseableHttpResponse response = httpClient.execute(request)) { // 获取状态码 int statusCode = response.getStatusLine().getStatusCode(); // 获取响应体 HttpEntity entity = response.getEntity(); if (entity != null) { String content = EntityUtils.toString(entity, "UTF-8"); System.out.println(content); // 输出网页内容 } }
带请求头的POST请求
// 创建HttpClient实例(含连接池) PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(200); // 最大连接数 CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .build(); // 构造POST请求 HttpPost post = new HttpPost("https://api.example.com/data"); post.setHeader("Content-Type", "application/json"); post.setHeader("User-Agent", "Mozilla/5.0"); // 设置请求体 StringEntity entity = new StringEntity( "{"key":"value"}", ContentType.APPLICATION_JSON); post.setEntity(entity); // 执行请求 try (CloseableHttpResponse response = httpClient.execute(post)) { // 处理响应... }
常见问题处理
问题类型 | 解决方案 |
---|---|
SSL证书验证失败 | SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()) |
IP被封禁 | 设置代理:RequestConfig.custom().setProxy(new HttpHost("proxy_ip", port)) |
乱码问题 | 显式指定编码:EntityUtils.toString(entity, "GBK") |
重定向循环 | 限制重定向次数:RequestConfig.custom().setRedirectsEnabled(false).build() |
实战案例:爬取天气数据
// 1. 创建带请求配置的HttpClient RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) // 连接超时 .setSocketTimeout(5000) // 读取超时 .setRedirectsEnabled(true) // 允许重定向 .build(); CloseableHttpClient client = HttpClients.custom() .setDefaultRequestConfig(config) .build(); // 2. 构造带UA的GET请求 HttpGet get = new HttpGet("https://api.weather.com/v1/city/beijing"); get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0)"); // 3. 执行请求并解析JSON try (CloseableHttpResponse response = client.execute(get)) { String json = EntityUtils.toString(response.getEntity()); JSONObject obj = new JSONObject(json); // 需引入fastjson库 System.out.println("温度:" + obj.getJSONObject("data").getDouble("temp")); }
问题与解答
Q1:HttpClient与Jsoup有什么区别?
A1:HttpClient负责网络请求层,用于获取网页HTML内容;Jsoup负责HTML解析层,用于提取和操作DOM元素,两者通常配合使用,HttpClient获取原始HTML,Jsoup解析结构化数据。
Q2:如何处理需要登录的网页爬取?
A2:需先发送登录请求获取会话Cookie,常见方法:
- 使用
HttpPost
提交用户名密码 - 从响应头中提取
Set-Cookie
值 - 后续请求携带该Cookie(通过
HttpClient
的默认CookieStore自动管理)