Java网络爬虫技术《一》 HttpClient

2026-06-20 20:47:11 / 五人足球世界杯

HttpClient

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。所以要想爬取网络资源,就要使用Http协议访问网页。

HttpClient 分为 无参GET请求、有参GET请求、无参POST请求、有参POST请求。

无参GET请求:类似普通的主页连接,没有附带任何参数的网页

HttpGet httpGet = new HttpGet("https://www.baidu.com/");

有参GET请求:附带有参数的连接,如搜索、分类功能的网页

HttpGet httpGet = new HttpGet("https://search.jd.com/Search?keyword=Java");

无参POST请求:跟GET有参请求相同

HttpPost httpPost = new HttpPost("https://www.baidu.com/");

有参POST请求: url地址没有参数,参数keys=java放到表单中进行提交

// 创建HttpGet请求

HttpPost httpPost = new HttpPost("https://search.jd.com/");

// 声明存放参数的List集合

List params = new ArrayList();

params.add(new BasicNameValuePair("keys", "java"));

// 创建表单数据Entity

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

// 设置表单Entity到httpPost请求对象中

httpPost.setEntity(formEntity);

入门程序

IDEA环境配置

org.apache.httpcomponents

httpclient

4.5.3

org.slf4j

slf4j-log4j12

1.7.25

加入 log4j.properties资源文件

log4j.rootLogger=DEBUG,A1

log4j.logger.cn.itcast = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

编写代码

public static void main(String[] args) throws Exception {

// 创建 HttpClient 对象

CloseableHttpClient httpClient = HttpClients.createDefault();

// 创建 HTTPGET 请求

HttpGet httpGet = new HttpGet("https://www.baidu.com/");

// 使用 HttpClient 发起请求

CloseableHttpResponse response = httpClient.execute(httpGet);

// 判断响应状态码是否为200(200指OK,,网页请求成功)

if (response.getStatusLine().getStatusCode() == 200) {

// 先把网页保存成String,解析获取字符集,将网页中文内容转换成对应字符集,再转换成统一的字符集utf-8

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

}

输出结果为网页的源码,可自行演示

HttpClient 连接池

跟线程、数据库连接一样,都需要一定数量的连接池,如果每次请求都要创建 HttpClient ,就会有频繁创建和销毁的问题,所以可以使用连接池来解决这种问题。

public static void main(String[] args) {

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

// 设置最大连接数

cm.setMaxTotal(200);

// 设置每个主机的并发数

cm.setDefaultMaxPerRoute(20);

TestGet(cm);

}

private static void TestGet(PoolingHttpClientConnectionManager cm) {

CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

HttpGet httpGet = new HttpGet("https://www.baidu.com/");

CloseableHttpResponse response = null;

try {

response = httpClient.execute(httpGet);

// 判断状态码是否是200

if (response.getStatusLine().getStatusCode() == 200) {

// 解析数据

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content.length());

}

} catch (Exception e) {

e.printStackTrace();

} finally {

//释放连接

if (response == null) {

try {

response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

此外,由于网络等原因,请求速度会变慢,所以我们得自定义具体事件,可以通过设置RequestConfig参数,再通过HTTPGET进行设置就行了。

// 设置请求参数

RequestConfig requestConfig = RequestConfig.custom()

.setConnectTimeout(1000)//设置创建连接的最长时间

.setConnectionRequestTimeout(500)//设置获取连接的最长时间

.setSocketTimeout(10 * 1000)//设置数据传输的最长时间

.build(); // 还有更多参数,如线程等,有需要请自行查阅资料

httpGet.setConfig(requestConfig);