HttpClient是客户端的http通信实现库,这个类库的作用是接收和发送http报文,使用这个类库,它相比传统的 HttpURLConnection,增加了易用性和灵活性,我们对于http的操作会变得简单一些。
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
HttpClient 支持了在 HTTP / 1.1
规范中定义的所有 HTTP 方法:GET
,HEAD
,POST
,PUT
,DELETE
,TRACE
和 OPTIONS
。对于每个方法类型,都有一个特定的类来支持:HttpGet
, HttpHead
,HttpPost
, HttpPut
,HttpDelete
, HttpTrace
,和 HttpOptions
。
官网地址:https://hc.apache.org/
maven仓库:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient
HttpGet httpGet = new HttpGet("https://www.ygang.top");
HttpResponse response = HttpClient.execute(httpGet);
HttpEntity resEntity = response.getEntity();
response.close();
httpClient.close();
Entity 是HttpClient中的一个特别的概念,所有的Entity都实现了HttpEntity
接口,输入是一个Entity,输出也是一个Entity 。这和HttpURLConnection的流有些不同,但是基本理念是相通的。HttpClient提供给我们一个工具类 EntityUtils
,可以很方便的操作Entity。
String urlTest = "https://www.ygang.top";
// 1、创建httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 2、创建HttpGet
HttpGet httpGetTest1 = new HttpGet(urlTest);
// 3、请求执行,获取响应
CloseableHttpResponse response = httpclient.execute(httpGetTest1);
System.out.println(response);
// 4、获取响应实体
HttpEntity entityTest = response.getEntity();
System.out.println(EntityUtils.toString(entityTest,"utf-8"));
// 5、关闭资源
response.close();
httpclient.close();
HttpGet httpget = new HttpGet("http://www.google.com/search?h1=1234&h2=5678");
// 使用URLBuilder来简化URI的创建
URI uri = null;
try {
uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("h1", "1234")
.setParameter("h2", "5678")
.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
HttpGet httpget = new HttpGet(uri);
String url = "https://www.ygang.top";
String jsonString = "{\"name\":\"tom\"}";
// 1、创建HttpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、创建HttpPost
HttpPost httpPost = new HttpPost(url);
// 3、设置请求头
httpPost.setHeader("x-appid","test");
httpPost.setHeader("Content-type","application/json");
// 4、设置请求体
StringEntity requestEntity = new StringEntity(jsonString);
httpPost.setEntity(requestEntity);
// 5、执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
// 6、解析响应数据
HttpEntity responseEntity = response.getEntity();
String result = EntityUtils.toString(requestEntity, StandardCharsets.UTF_8);
System.out.println(result);
// 7、关闭资源
response.close();
httpClient.close();