ITPub博客

首页 > > > 使用HttpClient工具来发送Http请求

使用HttpClient工具来发送Http请求

作者:duanhao 时间:2019-11-22 15:06:45 0 删除 编辑

一、使用HttpClient工具来发送Http请求

1.简介

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

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


2.应用场景


​


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
public void testHttpClient() throws IOException {

//1.获得HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建请求对象,如果是post请求 HttpPost 如果是get请求 HttpGet对象
String uri = "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"));
}


}

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2019-09-06

  • 博文量
    739
  • 访问量
    25541