一 HttpClient简介
在JDK中java.net包下提供了用户HTTP访问的基本功能,但是它缺少灵活性或许多应用所需要的功能。
HttpClient起初是Apache Jakarta Common 的子项目。用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。2007年成为顶级项目。
通俗解释:HttpClient可以实现使用Java代码完成标准HTTP请求及响应。
二 代码实现
2.1服务端
新建项目HttpClientServer
依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.11.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
新建控制器
@Controller
public class DemoController {
@RequestMapping("/demo")
@ResponseBody
public String demo(String param){
return param + "yqq";
}
}
2.2客户端
新建HttpClientDemo项目
添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.11.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</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();
}
}
}