实际集成

获取restTemplate实例,封装方法

package com.quant.api.utils.restTemplate;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate; import java.util.List;
import java.util.Map; /**
* @program: api
* @description:
* @author: TheEternity Zhang
* @create: 2019-06-04 18:00
*/
public class RestTemplateUtil {
/**
* 发送表单参数的post请求
*
* @param url 请求url
* @param param 参数
* @param respType 返回类型
* @return T
*/
public static <T> T postForm(String url, Map<String, List<Object>> param, Class<T> respType) {
return getRestInstance().postForEntity(url, getHttpEntity(param, false), respType).getBody();
} /**
* 发送表单参数的异步post请求
*
* @param url 请求url
* @param callback 回调接口
* @param respType 返回类型
*/
public static <T> void asyncPostForm(String url, Map<String, List<Object>> param,
Class<T> respType, ListenableFutureCallback<ResponseEntity<T>> callback) {
getAsyncRestInstance().postForEntity(url, getHttpEntity(param, false), respType).addCallback(callback);
} /**
* 发送表单有参数get请求
*
* @param url 请求url
* @param param 参数对象
* @param respType 返回类型
* @return T
*/
public static <T> T getForm(String url, Class<T> respType, Map<String,String> param) {
return getRestInstance().getForEntity(url, respType, param).getBody();
} /**
* @Description: 发送表单无参数的get请求
* @Param: [url, param, respType]
* @return: T
* @Author: tonyzhang
* @Date: 2019-01-18 17:23
*/
public static <T> T getForm(String url, Class<T> respType) {
return getRestInstance().getForObject(url, respType);
} /**
* 获取HttpEntity实例对象
*
* @param param 参数对象
* @param isJson true 发送json请求,false发送表单请求
* @return HttpEntity
*/
private static <P> HttpEntity<P> getHttpEntity(P param, boolean isJson) {
HttpHeaders headers = new HttpHeaders();
if (isJson) {
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
} else {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
} return new HttpEntity<>(param, headers);
} /*-----------------生产单例对象,方便自定义如何构造对象------------------*/ private static RestTemplate restInit() {
//设置连接超时和读取超时时间
SimpleClientHttpRequestFactory factory=new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000);
factory.setReadTimeout(5000);
RestTemplate restTemplate = new RestTemplate(factory);
FormHttpMessageConverter fastConverter = new FormHttpMessageConverter();
WxMappingJackson2HttpMessageConverter wmc=new WxMappingJackson2HttpMessageConverter();
restTemplate.getMessageConverters().add(fastConverter);
restTemplate.getMessageConverters().add(wmc);
return restTemplate;
} private static AsyncRestTemplate asyncRestInit() {
return new AsyncRestTemplate();
} private static RestTemplate getRestInstance() {
return RestSingle.INSTANCE;
} private static AsyncRestTemplate getAsyncRestInstance() {
return AsyncRestSingle.INSTANCE;
} private static class RestSingle {
private static final RestTemplate INSTANCE = restInit();
} private static class AsyncRestSingle {
private static final AsyncRestTemplate INSTANCE = asyncRestInit();
}
}

增加一个MessageConverter

package com.quant.api.utils.restTemplate;

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.util.ArrayList;
import java.util.List; /**
* @program: api
* @description: 封装转换器, 添加更多类型的支持
* @author: TheEternity Zhang
* @create: 2019-06-05 11:13
*/
public class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
public WxMappingJackson2HttpMessageConverter(){
List<MediaType> mediaTypes=new ArrayList<>();
//添加text/html类型的支持
mediaTypes.add(MediaType.TEXT_HTML);
//添加text/plain类型的支持.微信接口会用到
mediaTypes.add(MediaType.TEXT_PLAIN);
setSupportedMediaTypes(mediaTypes);
}
}

参考

简介:

spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接,我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。

RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP library。

其实spring并没有真正的去实现底层的http请求(3次握手),而是集成了别的http请求,spring只是在原有的各种http请求进行了规范标准,让开发者更加简单易用,底层默认用的是jdk的http请求。

RestTemplate的优缺点:

优点:

连接池、超时时间设置、支持异步、请求和响应的编解码

缺点:

依赖别的spring版块、参数传递不灵活

springboot集成RestTemplate:

导入依赖:(其实他是spring集成好的,这个一般的springboot项目已经由此包了)

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

在启动类同包下创建RestTemplate.java类

@Configuration
public class RestTemplateConfig { @Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
} @Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
} }

然后在Service类中注入使用即可

@Service
public class demoService { @Autowired
private RestTemplate restTemplate; public String get(Integer id){
return restTemplate.getForObject("http://localhost:8080/user?userId=id",String.class);
}
}

RestTemplate定义了36个与REST资源交互的方法,其中的大多数都对应于HTTP的方法。 

其实,这里面只有11个独立的方法,其中有十个有三种重载形式,而第十一个则重载了六次,这样一共形成了36个方法。

delete() 在特定的URL上对资源执行HTTP DELETE操作

exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的

execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象

getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象

getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象

postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的

postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象

headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头

optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息

postForLocation() POST 数据到一个URL,返回新创建资源的URL

put() PUT 资源到特定的URL

getForEntity

get请求就和正常在浏览器url上发送请求一样

下面是有参数的get请求

@GetMapping("getForEntity/{id}")
public User getById(@PathVariable(name = "id") String id) {
ResponseEntity<User> response = restTemplate.getForEntity("http://localhost/get/{id}", User.class, id);
User user = response.getBody();
return user;
}

getForObject

getForObject 和 getForEntity 用法几乎相同,指示返回值返回的是 响应体,省去了我们 再去 getBody()

@GetMapping("getForObject/{id}")
public User getById(@PathVariable(name = "id") String id) {
User user = restTemplate.getForObject("http://localhost/get/{id}", User.class, id);
return user;
}

postForEntity

@RequestMapping("saveUser")
public String save(User user) {
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost/save", user, String.class);
String body = response.getBody();
return body;
}

postForObject

用法与 getForObject 一样

如果遇到 postForObject 方法在 Controller 接受不到参数问题 请参考的的另一篇博客 :

https://blog.csdn.net/weixin_40461281/article/details/83472648

exchange

@PostMapping("demo")
public void demo(Integer id, String name){ HttpHeaders headers = new HttpHeaders();//header参数
headers.add("authorization",Auth);
headers.setContentType(MediaType.APPLICATION_JSON); JSONObject obj = new JSONObject();//放入body中的json参数
obj.put("userId", id);
obj.put("name", name); HttpEntity<JSONObject> request = new HttpEntity<>(content,headers); //组装 ResponseEntity<String> response = template.exchange("http://localhost:8080/demo",HttpMethod.POST,request,String.class);
}

其余的方法用法也都差不多 , 在此就不细说了

参考

原文:https://blog.csdn.net/weixin_40461281/article/details/83540604

原文:https://blog.csdn.net/QiaoRui_/article/details/80453799

至此就可以直接调用API使用了,具体的调用及原理,连接池配置等可以参考如下收集的几个很棒的文章

需要注意的是参数一定要用map否则接受的时候会有“null”这种情况而不是null

RestTemplate官方网站:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

很好的介绍文章:       https://www.xncoding.com/2017/07/06/spring/sb-restclient.html

http://ju.outofmemory.cn/entry/341530

https://my.oschina.net/lifany/blog/688889

关于配置http连接池原理的文章:

https://blog.csdn.net/umke888/article/details/54881946

https://www.cnblogs.com/likaitai/p/5431246.html

springboot2.0集成RestTemplate的更多相关文章

  1. SpringBoot2.0集成FastDFS

    SpringBoot2.0集成FastDFS 前两篇整体上介绍了通过 Nginx 和 FastDFS 的整合来实现文件服务器.但是,在实际开发中对图片或文件的操作都是通过应用程序来完成的,因此,本篇将 ...

  2. (补漏)Springboot2.0 集成shiro权限管理

    原文Springboot2.0 集成shiro权限管理 一.关于停止使用外键. 原本集成shiro建立用户.角色.权限表的时候使用了外键,系统自动创建其中两个关联表,用@JoinTable.看起来省事 ...

  3. SpringBoot2.0集成Shiro

    1.shiro的三个核心概念: 1)Subject:代表当前正在执行操作的用户,但Subject代表的可以是人,也可以是任何第三方系统帐号.当然每个subject实例都会被绑定到SercurityMa ...

  4. springboot2.0集成shiro出现ShiroDialect报错找不到AbstractTextChildModifierAttrPr

    @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } 报错出现找不到org/thymeleaf/process ...

  5. springboot2.0 集成elasticsearch,实现检索、分页、排序

    springboot整合es的方式: transport方式(7.0弃用,8.0移除) spring-data(完全当做数据库来用,无法全部支持es,内部也是基于transport,包装后使用非常简单 ...

  6. Springboot2.0 集成shiro权限管理

    在springboot中结合shiro教程搭建权限管理,其中几个小细节的地方对新手不友好,伸手党更是无法直接运行代码,搭建过程容易遇坑,记录一下.关键的地方也给注释了. 版本:springboot版本 ...

  7. SpringBoot2.0集成WebSocket,实现后台向前端推送信息

    感谢作者,支持原创: https://blog.csdn.net/moshowgame/article/details/80275084 什么是WebSocket? WebSocket协议是基于TCP ...

  8. springboot2.0集成webSocket

    WebSocket和http的区别? http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息. http链接分为短链接,长链接,短链接是每次请求都要三 ...

  9. SpringBoot集成RestTemplate

    先把原文列出来: springboot实战之常用http客户端整合 springboot2.0集成RestTemplate -----------开始------------ SpringBoot应用 ...

随机推荐

  1. webpack-高级-发布策略

    webpack的发布策略 在实际开发中,一般会有两套项目方案: 一套是开发期间的项目,包含了测试文件.测试数据.开发工具.测试工具等相关配置,有利于项目的开发和测试,但是这些文件仅用于开发,发布项目时 ...

  2. bitset 位运算

    1. 判断一个数是否是2的方幂n > 0 && ((n & (n - 1)) == 0 ) 解释((n & (n-1)) == 0): 如果A&B==0, ...

  3. curl模拟提交

    function curl_post($url, $post){ $options = array( CURLOPT_RETURNTRANSFER =>true, CURLOPT_HEADER ...

  4. TestNG单元测试与使用详解

    TestNG的基本注解与执行顺序 在类里编辑程序时,在@Test后面,摁 alt+回车,选择对应的插件,可以把目前用到的插件自动添加到 pom.xml 文件中,如下面的testng,每摁一次,就多添加 ...

  5. django 创建管理员用户

    7.2 create 创建管理员用户: python manage.py run server python manage.py createsuperuser password :123456789 ...

  6. 刷题11. Container With Most Water

    一.题目说明 11.Container With Most Water,这个题目难度是Medium. 二.我的做法 乍一看,简单啊,两个for循环就可以了,我在本地写的. #include<io ...

  7. Smart License

    思科启动了通过构建思科智能软件管理器门户来简化客户许可管理的计划. 它可以帮助客户了解他们购买的许可证以及他们使用的许可证. 其他各种思科产品已经启用Smart Enabled,随着此版本(我这里学习 ...

  8. WLC license管理

    关于控制器的license,可以参考对应平台的Datasheet: Cisco 2504 WLC Cisco 3504 WLC Cisco 5508 WLC Cisco 5520 WLC Cisco ...

  9. JenKins docker 集群

    //tag 桉树有时间来搞 **阿斯蒂 啊 阿斯蒂

  10. Jmeter_选项_函数助手_RandomString的用法

    1.用处:测试账户注册可以通过随机生成数实现,而不需要Excel手动输入, 缺点:随机生成数可能会重复 优点:不需要使用CSV config 或者excel ,txt格式 2.举例:之前我们通过CSV ...