Java网络爬虫技术《一》 HttpClient

news/2024/7/19 9:20:59 标签: java, http, 爬虫
http://www.w3.org/2000/svg" style="display: none;">

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<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keys", "java"));

//	创建表单数据Entity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

//	设置表单Entity到httpPost请求对象中
httpPost.setEntity(formEntity);

入门程序

IDEA环境配置

<dependencies>
<!-- HttpClient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

<!-- 日志 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>

加入 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);

http://www.niftyadmin.cn/n/1620560.html

相关文章

Java Code Style Guidelines

标题Java Code Style GuidelinesNaming ConventionsCamelCaseClass and interface namesMethod namesVariable namesPackage namesFormat conventionsIndentation and braces { }DocumentationKinds of comments in Java, including Javadoc commentsDont over-commentClass in…

js比较操作符 结果是Boolean值?

>大于 <小于 >大于等于 <小于等于 相对比较 绝对比较 !(相当于相对比较) ! 不等于(相当于绝对比较)在严格比较下 null不等于undefined 是成立 console.log(null ! undefined) // true相对比较 [] false console.log([] ! false) // false 复制代码console.log(2 …

Java网络爬虫技术《二》Jsoup

Jsoup 当我们成功抓取到页面数据了之后&#xff0c;还需要对抓取的数据进行解析&#xff0c;而刚好&#xff0c;Jsoup 是一款专门解析 html 页面的技术。Jsoup是一款基于 Java 的HTML 解析器&#xff0c;可直接解析某个 URL 地址、HTML 、文本内容。可以通过DOM、CSS以及类似于…

Go 调用外部命令

这里填写标题Go 调用外部命令引子运行命令显示输出显示到标准输出输出到文件发送到网络保存到内存对象中输出到多个目的地运行命令, 获取输出分别获取标准输出和标准错误标准输入环境变量检查命令是否存在封装总结参考print output in real timeos/exec: Output and CombinedOu…

Tomcat.md

Tomcat Tomcat的目录结构&#xff1a; bin&#xff1a;脚本及启动时用到的类1ib&#xff1a;类库conf&#xff1a;配置文件webapps&#xff1a;应用程序默认部署目录work&#xff1a;工作目录temp&#xff1a;临时文件目录配置文件 server.xml&#xff1a;主配置文件context.xm…

Java实现爬取京东手机数据

Java实现爬取京东手机数据 最近看了某马的Java爬虫视频&#xff0c;看完后自己上手操作了下&#xff0c;基本达到了爬数据的要求&#xff0c;HTML页面源码也刚好复习了下&#xff0c;之前发布两篇关于简单爬虫的文章&#xff0c;也刚好用得上。项目没什么太难的地方&#xff0…

WebMagic 爬虫技术

WebMagic WebMagic 介绍 WebMagic基础架构 Webmagic 的结构分为 Downloader、PageProcessor、Scheduler、Pipeline四大组件&#xff0c;并由 Spider将他们彼此组织起来。这四种组件对应爬虫生命周期中的下载、处理、管理和持久化等功能。Spider将这几个组件组织起来&#xf…

Java 爬取 51job 数据 WebMagic实现

Java 爬取 51job 数据 一、项目Maven环境配置 相关依赖 jar 包配置 <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.2.RELEASE</version> </parent&g…