SpringBoot使用HttpClient
一、HttpClient
两个系统间如何互相访问?两个tomcat上的项目如何互相访问
采用HttpClient实现跨系统的接口调用。
1
1.2、 什么是HttpClient
官网:http://hc.apache.org/index.html
特点:
HttpClient别名:HttpComponents
HttpClient可以发送get、post、put、delete、…等请求
1.3、 HttpClient入门案例
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
1.3.1、 发起Get请求
1创建一个客户端 CloseableHttpClient
2创建一个get方法请求实例 HttpGet
3发送请求 execute
4获取响应的头信息
5获取响应的主题内容
6关闭响应对象
使用HttpClient发起Get请求的案例代码:
public class DoGET {
public static void main(String[] args) throws Exception {
// 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建HttpGet请求,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
CloseableHttpResponse response = null;
try {
// 执行请求,相当于敲完地址后按下回车。获取响应
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应,获取数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
// 关闭资源
response.close();
}
// 关闭浏览器
httpclient.close();
}
}
}
1.3.2、 带参数的Get请求
1创建一个客户端 CloseableHttpClient
2 通过URIBuilder传递参数
3创建一个get方法请求实例 HttpGet
4发送请求 execute
5获取响应的头信息
6获取响应的主题内容
7关闭响应对象
访问网站的爬虫协议:
public class DoGETParam {
public static void main(String[] args) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建URI对象,并且设置请求参数
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// HttpGet get = new HttpGet("http://www.baidu.com/s?wd=java");
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}
1.3.4、 带参数POST请求
/*
* 演示:使用HttpClient发起带有参数的POST请求
*/
public class DoPOSTParam {
public static void main(String[] args) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求,访问开源中国
HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
// 根据开源中国的请求需要,设置post请求参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
parameters.add(new BasicNameValuePair("fromerr", "8bDnUWwC"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应体
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
// 关闭浏览器
httpclient.close();
}
}
}
SpringBoot官方并没有对HttpClient的启动器。所以我们需要自己完成配置
不过,SpringBoot虽然没有提供启动器,但是却提供了一个对Restful服务进行调用的模板类:RestTemplate,底层可以使用HttpClient来实现。有了这个我们就无需自己定义APIService了。
1、导入maven坐标
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
2、在application.properties添加如下配置:
#The config for HttpClient
http.maxTotal=300
http.defaultMaxPerRoute=50
http.connectTimeout=1000
http.connectionRequestTimeout=500
http.socketTimeout=5000
http.staleConnectionCheckEnabled=true
创建HttpClientConfig类–类似util(配置,无需搞懂,拿来即用)
/**
* HttpClient的配置类
*
*/
@Configuration
@ConfigurationProperties(prefix = "http", ignoreUnknownFields = true)
public class HttpClientConfig {
private Integer maxTotal;// 最大连接
private Integer defaultMaxPerRoute;// 每个host的最大连接
private Integer connectTimeout;// 连接超时时间
private Integer connectionRequestTimeout;// 请求超时时间
private Integer socketTimeout;// 响应超时时间
/**
* HttpClient连接池
* @return
*/
@Bean
public HttpClientConnectionManager httpClientConnectionManager() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return connectionManager;
}
/**
* 注册RequestConfig
* @return
*/
@Bean
public RequestConfig requestConfig() {
return RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)
.build();
}
/**
* 注册HttpClient
* @param manager
* @param config
* @return
*/
@Bean
public HttpClient httpClient(HttpClientConnectionManager manager, RequestConfig config) {
return HttpClientBuilder.create().setConnectionManager(manager).setDefaultRequestConfig(config)
.build();
}
/**
* 使用连接池管理连接
* @param httpClient
* @return
*/
@Bean
public ClientHttpRequestFactory requestFactory(HttpClient httpClient) {
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
/**
* 使用HttpClient来初始化一个RestTemplate
* @param requestFactory
* @return
*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
RestTemplate template = new RestTemplate(requestFactory);
List<HttpMessageConverter<?>> list = template.getMessageConverters();
for (HttpMessageConverter<?> mc : list) {
if (mc instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
}
}
return template;
}
public Integer getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(Integer maxTotal) {
this.maxTotal = maxTotal;
}
public Integer getDefaultMaxPerRoute() {
return defaultMaxPerRoute;
}
public void setDefaultMaxPerRoute(Integer defaultMaxPerRoute) {
this.defaultMaxPerRoute = defaultMaxPerRoute;
}
public Integer getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Integer getConnectionRequestTimeout() {
return connectionRequestTimeout;
}
public void setConnectionRequestTimeout(Integer connectionRequestTimeout) {
this.connectionRequestTimeout = connectionRequestTimeout;
}
public Integer getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
}
}
引入RestTemplate模板
在FixedAreaController中,引入RestTemplate模板,发送rest请求
@Autowired
private RestTemplate restTemplate;
1
2
编写FixedAreaController的方法
// 查询未关联定区列表
@GetMapping("/findNoAssociationCustomers")
public ResponseEntity<String> findNoAssociationCustomers() {
// 使用HttpClient调用 远程接口
String url = Constants.CRM_MANAGEMENT_HOST + "/customer/noAssociationCustomers";
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
HttpStatus statusCode = result.getStatusCode();
String body = result.getBody();
return new ResponseEntity<>(body,statusCode);
}
1
public class Constants {
public static final String BOS_MANAGEMENT_HOST = "http://localhost:8088";
public static final String CRM_MANAGEMENT_HOST = "http://localhost:8090";
private static final String BOS_MANAGEMENT_CONTEXT = "/bos_management";
private static final String CRM_MANAGEMENT_CONTEXT = "/crm_management";
}
1
// 查询已关联到定区的用户列表
@GetMapping(value = "/findHasAssociationFixedAreaCustomers")
public ResponseEntity<String> findHasAssociationFixedAreaCustomers(@RequestParam("id")String fixedAreaId) {
// 使用HttpClient调用 接口
String url = Constants.CRM_MANAGEMENT_HOST + "/customer/associationFixedAreaCustomers?fixedAreaId="+fixedAreaId;
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
// return result;
HttpStatus statusCode = result.getStatusCode();
String body = result.getBody();
return new ResponseEntity<>(body,statusCode);
}
SpringBoot使用HttpClient相关推荐
- springboot 访问httpclient接口
使用jar: <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>h ...
- springboot RestTemplate httpclient
RestTemplate是spring支持的一个请求http rest服务的模板对象,性质上有点像jdbcTemplate RestTemplate底层还是使用的httpclient(org.apac ...
- java爬虫案例——SpringBoot使用HttpClient、Jsoup爬取京东手机数据
文章目录 前言 一.准备工作 二.项目文件 1.项目依赖 2.项目配置文件 3.pojo 4.dao接口 5.service接口及其实现类 6.HttpClient封装工具类 7.爬取任务实现 8.启 ...
- SpringBoot以及网关服务配置部署和发布
云服务 aliyunCloud,tencentCloud ...... 做任何事情之前,先考虑以下几个方面: 1细节决定成败 2墨菲定律 一.工具管理服务搭建 1.Maven搭建 ...... ...
- 玩转springboot2.x之自定义项目内自动配置
专题系列分类:玩转SpringBoot2.x系列教程 SpringBoot 为我们提供自动配置相关操作,SpringBoot 大量starter依赖就是通过自动配置来实现的.我在上一篇博客 玩转spr ...
- Timeout waiting for connection from pool
springboot使用httpclient在高并发的情况下会出现Timeout waiting for connection from pool,经测试是因为和有些银行接口建立链接时会超时,有些则不 ...
- 微信扫码登录实战(附代码)
来源:JAVA葵花宝典 导读:由于微信端流量比较足,所以扫码登录系统功能也受到了很多系统的青睐,本文就来详细的解开该技术的面纱. 演示效果 准备工作 1. 需要一个微信开放平台账号,并创建一个网站应用 ...
- 【SpringBoot】关闭HttpClient无用日志
环境: SpringBoot pom依赖了apache.commons.HttpClient: <!--httpclient--> <dependency><groupI ...
- SpringBoot通联支付接口实现案例之Httpclient(后端篇)
首先需要两个一个 <dependency><groupId>org.apache.httpcomponents</groupId><artifactId> ...
最新文章
- 关于网页显示乱码问题的一些个人见解(PHP、JSP...)
- Oracle函数列表速查
- 小技巧:远程连接共享文件密码错误
- java,list遍历赋值
- SAP Spartacus里的injector
- alientek ministm32液晶显示程序_佳显12864中文字库液晶专业生产液晶显示模块
- Web工程师修行笔记_必备单词(第三部)
- python多线程插入1万条数据
- python可以参加哪些竞赛_找出Python竞赛中可达到的分数的程序
- JavaScript如何进行文件上传
- 如何获取iphone的UUID
- 运动耳机哪些好用?专业运动耳机购买指南
- 物联网卡零售应用的真实案例
- 小猿日记 - 程序猿的日常日记(4)
- 多目标优化问题和遗传算法学习笔记
- hal系统命令 android,动态可用的 HAL | Android 开源项目 | Android Open Source Project...
- 数字电路之Verilog红绿灯设计
- 【2021版】吐血整理_专升本计算机文化基础—Word2010
- Java转Go语言 -12
- Python 实现 周志华 《机器学习》 BP算法(高级版)