简介
1.HttpClient主要用在SpringBoot分布式架构中,不同的项目模块之间的一个http通信,这是早期原始的一种用法。
使用步骤
1.创建一个cloud_parent父类项目。注意是SpringBoot项目,然后在里面创建两个子项目如下图
2.比如:由我们customer向provied项目发送请求
(1)在customer项目中导入httpClient依赖
<!-- httpclient依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
(2)创建一个配置类config
//Compent 把当前类交给spring
//Controller
//Service
//Mapper
//@Configuration //配置类注解,代码版配置文件
@Configuration
public class Config {
//开启restTemplate
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
(3)在controller层创建一个类,与前端打交道
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class CustomController {
@GetMapping("/cus")
public void ToIndex(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://localhost:8082/pro");
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(4)第二个项目的controller层
@RestController
public class ProvController {
@GetMapping("/pro")
public String ToIndex(){
return "hello,httpclien";
}
}
(5)然后启动第一个项目,调用相关接口,就可以向我们第二个项目发送http请求了。这就是简单的一个应用。后期被SpringCloud中的restTemplate代替。