Spring Boot 之httpClient使用
版权声明:本文为博主原创文章,转载时请在文章最前方附上本文地址。 https://blog.csdn.net/qq_35033270/article/details/80112085
超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。所有的WWW文件都必须遵守这个标准。而HttpClient是可以支持http相关协议的工具包,它有如下功能:
1.实现了所有的http方法(GET,POST,PUT,HEAD 等)
2.支持自动转向
3.支持 HTTPS 协议
4.支持代理服务器等
既然HttpClient使用这么广泛,则本文讲解下Spring Boot 中怎么使用HttpClient.如下:
一.引入相关依赖
<!-- http所需包 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<!-- /http所需包 -->
<!-- 数据解析所需包 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!-- /数据解析所需包 -->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
二.编写相关工具类
写个http的工具类,以便业务代码直接调用,如下:
/**
* Http工具类
*/
public class HttpUtils {
/**
* 发送POST请求
* @param url 请求url
* @param data 请求数据
* @return 结果
*/
@SuppressWarnings("deprecation")
public static String doPost(String url, String data) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000).setConnectTimeout(20000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
String context = StringUtils.EMPTY;
if (!StringUtils.isEmpty(data)) {
StringEntity body = new StringEntity(data, "utf-8");
httpPost.setEntity(body);
}
// 设置回调接口接收的消息头
httpPost.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
context = EntityUtils.toString(entity, HTTP.UTF_8);
} catch (Exception e) {
e.getStackTrace();
} finally {
try {
response.close();
httpPost.abort();
httpClient.close();
} catch (Exception e) {
e.getStackTrace();
}
}
return context;
}
/**
* 解析出url参数中的键值对
* @param url url参数
* @return 键值对
*/
public static Map<String, String> getRequestParam(String url) {
Map<String, String> map = new HashMap<String, String>();
String[] arrSplit = null;
// 每个键值为一组
arrSplit = url.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
// 解析出键值
if (arrSplitEqual.length > 1) {
// 正确解析
map.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (arrSplitEqual[0] != "") {
map.put(arrSplitEqual[0], "");
}
}
}
return map;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
三.业务代码中使用
业务中代码使用,拼装请求Url和请求数据,就可以调用工具类里的doPost()方法开始直接使用咯。如下:
private String getFileStorePath(String courtId, String seesionId){
String fileStorePath = StringUtils.EMPTY;
//请求参数
String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}";
String fileServiceUrl="http://111.11.11.11:8086";
//发送请求,获取结果
String result = HttpUtils.doPost(fileServiceUrl + "/ms-service/voice/search", data);
if(StringUtils.isNotBlank(result)){
com.alibaba.fastjson.JSONObject jsonobject = JSON.parseObject(result);
fileStorePath = jsonobject.getString("path");
logger.info("fileStorePath = " + fileStorePath);
}
return fileStorePath;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
如有不当之处,烦请斧正,一起沟通。
原文:https://blog.csdn.net/qq_35033270/article/details/80112085
Spring Boot 之httpClient使用的更多相关文章
- spring boot 整合 HttpClient
第一步:引入HttpClient 的jar包 1.httpClient 5.0 开始支持异步(Async)请求: 2.httpclient 版本过低上传文件会出,原因是 org.apache.http ...
- Spring Boot 中使用 HttpClient 进行 POST GET PUT DELETE
有的时候,我们的 Spring Boot 应用需要调用第三方接口,这个接口可能是 Http协议.可能是 WebService.可能是 FTP或其他格式,本章讨论 Http 接口的调用. 通常基于 Ht ...
- spring/spring boot/spring cloud开发总结
背景 针对RPC远程调用,都在使用dubbo.dubbox等,我们也是如此.由于社区暂停维护.应对未来发展,我们准备尝试新技术(或许这时候也不算什么新技术了吧),选择使用了spring ...
- Spring Boot 添加Shiro支持
前言: Shiro是一个权限.会话管理的开源Java安全框架:Spring Boot集成Shiro后可以方便的使用Session: 工程概述: (工程结构图) 一.建立Spring Boot工程 参照 ...
- spring boot学习笔记
spring boot 是什么 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程. spring boot采用了“约定优于配置” ...
- Spring Boot使用RestTemplate消费REST服务的几个问题记录
我们可以通过Spring Boot快速开发REST接口,同时也可能需要在实现接口的过程中,通过Spring Boot调用内外部REST接口完成业务逻辑. 在Spring Boot中,调用REST Ap ...
- Spring Boot ConfigurationProperties validate
使用@Query可以在自定义的查询方法上使用@Query来指定该方法要执行的查询语句,比如:@Query("select o from UserModel o where o.uuid=?1 ...
- Spring Boot OAuth 2.0 客户端
在上一篇<OAuth 2.0 授权码请求>中我们已经可以获取到access_token了,本节将使用客户端来访问远程资源 配置资源服务器 授权服务器负责生成并发放访问令牌(access_t ...
- 我的自定义框架 || 基于Spring Boot || 第一步
今天在园子里面看到一位大神写的springboot做的框架,感觉挺不错,遂想起来自己还没有一个属于自己的框架,决定先将大神做好的拿过来,然后加入自己觉得需要的模块,不断完善 目前直接复制粘贴过来的,后 ...
随机推荐
- eclipse启动web应用 报错
错误:The origin server did not find a current representation for the target resource or is not willing ...
- Python学习(十八)—— 数据库(三)
转载自http://www.cnblogs.com/linhaifeng/articles/7356064.html 一.数据操作 1.插入数据INSERT 1. 插入完整数据(顺序插入) 语法一: ...
- Python 多进程multiprocessing
一.python多线程其实在底层来说只是单线程,因此python多线程也称为假线程,之所以用多线程的意义是因为线程不停的切换这样比串行还是要快很多.python多线程中只要涉及到io或者sleep就会 ...
- k8s 英文文档翻译
https://medium.com/google-cloud/understanding-kubernetes-networking-pods-7117dd28727
- sql 将一列一逗号分隔拼成字符串
select stuff((select ','+w.Waybillno from Web_Way_Waybill w where w.IsValid<>'Y' AND w.TruckOr ...
- 044 SimpleDateFormat的线程安全问题与解决方案
这个问题,以前好像写过,不过现在这篇文章,有一个重现的过程,还是值得读一读的. URL:SimpleDateFormat的线程安全问题与解决方案
- 002 如何在一台PC上装两个版本的python
在之前学习爬虫的时候,使用的是python2.7,现在主流已经是3.7了. 在这里,写了一下如何在2.7的基础上安装python3.6 一:检查python版本 1.cmd 二:安装python3 1 ...
- c#中的委託,匿名方法和lambda表達式
(原博)http://www.cnblogs.com/niyw/archive/2010/10/07/1845232.html 简介 在.NET中,委托,匿名方法和Lambda表达式很容易发生混淆.我 ...
- 利用Python中的mock库对Python代码进行模拟测试
这篇文章主要介绍了利用Python中的mock库对Python代码进行模拟测试,mock库自从Python3.3依赖成为了Python的内置库,本文也等于介绍了该库的用法,需要的朋友可以参考下 ...
- 【LeetCode算法-20】Valid Parentheses
LeetCode第20题 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determin ...