温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

好程序员Java教程分享使用HttpClient抓取页面内容

发布时间:2020-07-12 18:52:45 来源:网络 阅读:178 作者:wx5da18b5c4b01e 栏目:编程语言

好程序员Java教程分享使用HttpClient抓取页面内容,使用HttpClient工具来发送Http请求

1.简介
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。

HttpClient 相比传统 JDK 自带的 URLConnection,增加了易用性和灵活性,它不仅是客户端发送 HTTP 请求变得容易,而且也方便了开发人员测试接口(基于 HTTP 协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握 HttpClient 是很重要的必修内容,掌握 HttpClient 后,相信对于 HTTP 协议的了解会更加深入。

2.应用场景
点击并拖拽以移动​
好程序员Java教程分享使用HttpClient抓取页面内容
3.HttpClient工具的使用
1)添加依赖
<!-- Apache Http Begin -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>
<!-- Apache Http End -->

2)编写测试代码@Test
br/>@Test

//1.获得HttpClient对象

CloseableHttpClient client = HttpClients.
createDefault
();
//2.创建请求对象,如果是post请求 HttpPost 如果是get请求 HttpGet对象

String uri = "http://www.baidu.com";
HttpGet get = new HttpGet(uri);
//3.执行get请求,获得响应消息对象

CloseableHttpResponse response = client.execute(get);
//4.获取响应行

StatusLine statusLine = response.getStatusLine();
//5.获取状态码

int code = statusLine.getStatusCode();
if(code==200){
//响应成功

HttpEntity entity = response.getEntity();
//6.获取响应体中的内容

// InputStream is = entity.getContent();

// byte[] b = new byte[8192];

// int len = 0;

// while((len = is.read(b))!=-1){

// System.out.println(new String(b,0,len));

// }

// is.close();

System.
out
.println(EntityUtils.
toString
(entity, "utf-8"));
}

}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI