在JDK中java.net包下提供了用户HTTP访问的基本功能,但是它缺少灵活性或许多应用所需要的功能。
HttpClient起初是Apache Jakarta Common 的子项目。用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。2007年成为顶级项目。
通俗解释:HttpClient可以实现使用Java代码完成标准HTTP请求及响应。
新建项目HttpClientServer

<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.11.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
@Controller
public class DemoController {
@RequestMapping("/demo")
@ResponseBody
public String demo(String param){
return param + "yqq";
}
}
新建HttpClientDemo项目

<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.11.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.10version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
public class HttpClientDemo {
@Test
public void testGetDemo(){
//1.创建http工具(类似浏览器)发送请求,解析相应
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
//2.请求路劲
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
uriBuilder.addParameter("param","yn");
//3.创建httpGet请求对象
HttpGet get = new HttpGet(uriBuilder.build());
//4.创建相应对象
CloseableHttpResponse httpResponse = httpClient.execute(get);
//由于响应体是字符串,因此把HttpEntity类型转换为字符串,并设置编码字符集
String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
//输出结果
System.out.println(result);
//释放资源
httpResponse.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
