RestTemplate使用教程
原文地址:https://www.cnblogs.com/f-anything/p/10084215.html
一、概述
spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计原则与许多其他Spring *模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。
二、实现
RestTemplate包含以下几个部分:
- HttpMessageConverter 对象转换器
- ClientHttpRequestFactory 默认是JDK的HttpURLConnection
- ResponseErrorHandler 异常处理
- ClientHttpRequestInterceptor 请求拦截器
常规配置
public MyRestClientService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthorization("username", "password")
.setConnectTimeout(3000)
.setReadTimeout(5000)
.rootUri("http://api.example.com/")
.build();
}
ClientHttpRequestInterceptor
学习使用带有Spring RestTemplate的ClientHttpRequestInterceptor,以Spring AOP风格记录请求和响应头和主体。
拦截器记录请求和响应
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils; import java.io.IOException;
import java.nio.charset.Charset; public class RequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
{
logRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
logResponse(response); //Add optional additional headers
response.getHeaders().add("headerName", "VALUE"); return response;
} private void logRequest(HttpRequest request, byte[] body) throws IOException
{
if (log.isDebugEnabled())
{
log.debug("===========================request begin================================================");
log.debug("URI : {}", request.getURI());
log.debug("Method : {}", request.getMethod());
log.debug("Headers : {}", request.getHeaders());
log.debug("Request body: {}", new String(body, "UTF-8"));
log.debug("==========================request end================================================");
}
} private void logResponse(ClientHttpResponse response) throws IOException
{
if (log.isDebugEnabled())
{
log.debug("============================response begin==========================================");
log.debug("Status code : {}", response.getStatusCode());
log.debug("Status text : {}", response.getStatusText());
log.debug("Headers : {}", response.getHeaders());
log.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
log.debug("=======================response end=================================================");
}
}
}
注册ClientHttpRequestInterceptor
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(newBufferingClientHttpRequestFactory(clientHttpRequestFactory()));
restTemplate.setMessageConverters(Collections.singletonList(mappingJacksonHttpMessageConverter())); restTemplate.setInterceptors( Collections.singletonList(newRequestResponseLoggingInterceptor()) ); return restTemplate;
}
三、请求示例
GET
private static void getEmployees(){
final String uri = "http://localhost:8080/springrestexample/employees"; RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class); System.out.println(result);
}
使用RestTemplate定制HTTP头文件
private static void getEmployees(){
final String uri = "http://localhost:8080/springrestexample/employees"; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class); System.out.println(result);
}
Get请求获取响应为一个对象
private static void getEmployees(){
final String uri = "http://localhost:8080/springrestexample/employees";
RestTemplate restTemplate = new RestTemplate(); EmployeeListVO result = restTemplate.getForObject(uri, EmployeeListVO.class); System.out.println(result);
}
URL 参数
private static void getEmployeeById(){
final String uri = "http://localhost:8080/springrestexample/employees/{id}"; Map<String, String> params = new HashMap<String, String>();
params.put("id", "1"); RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class, params); System.out.println(result);
}
POST
private static void createEmployee(){
final String uri = "http://localhost:8080/springrestexample/employees"; EmployeeVO newEmployee = new EmployeeVO(-1, "Adam", "Gilly", "test@email.com"); RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class); System.out.println(result);
}
Submit Form Data
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "1"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, request, EmployeeVO.class);
System.out.println(result);
PUT
private static void updateEmployee(){
final String uri = "http://localhost:8080/springrestexample/employees/{id}"; Map<String, String> params = new HashMap<String, String>();
params.put("id", "2"); EmployeeVO updatedEmployee = new EmployeeVO(2, "New Name", "Gilly", "test@email.com"); RestTemplate restTemplate = new RestTemplate();
restTemplate.put ( uri, updatedEmployee, params);
}
Simple PUT
Foo updatedInstance = new Foo("newName");
updatedInstance.setId(createResponse.getBody().getId());
String resourceUrl =
fooResourceUrl + '/' + createResponse.getBody().getId();
HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
使用.exchange和请求回调
RequestCallback requestCallback(final Foo updatedInstance) {
return clientHttpRequest -> {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
clientHttpRequest.getHeaders().add(
HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
clientHttpRequest.getHeaders().add(
HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
};
}
DELETE
private static void deleteEmployee(){
final String uri = "http://localhost:8080/springrestexample/employees/{id}"; Map<String, String> params = new HashMap<String, String>();
params.put("id", "2"); RestTemplate restTemplate = new RestTemplate();
restTemplate.delete ( uri, params );
}
参考资料:
https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/
https://www.xncoding.com/2017/07/06/spring/sb-restclient.html
https://www.baeldung.com/rest-template
RestTemplate使用教程的更多相关文章
- Spring RestTemplate使用教程
简介 Spring'scentral class for synchronous client-side HTTP access.It simplifies communication with HT ...
- Spring RestTemplate 的介绍和使用-入门
RestTemplate是什么? 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单便捷的模板类来进 ...
- 关于java代码提交HTTP POST请求中文乱码的解决方法
首先说明下这些只是根据我工作常用经验的总结,可能不一定完全对,也不一定全面,但却是最通用的. JAVA里HTTP提交方式 httpurlconnection:jdk里自带的 httpclient:ap ...
- Spring Cloud Alibaba基础教程:支持的几种服务消费方式(RestTemplate、WebClient、Feign)
通过<Spring Cloud Alibaba基础教程:使用Nacos实现服务注册与发现>一文的学习,我们已经学会如何使用Nacos来实现服务的注册与发现,同时也介绍如何通过LoadBal ...
- SpringBoot图文教程17—上手就会 RestTemplate 使用指南「Get Post」「设置请求头」
有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1-Spr ...
- SpringBoot非官方教程 | 第十六篇:用restTemplate消费服务
转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot11-restTemplate/ 本文出自方志朋的 ...
- Spring Cloud Commons教程(二)Spring RestTemplate作为负载平衡器客户端
RestTemplate可以自动配置为使用功能区.要创建负载平衡RestTemplate创建RestTemplate @Bean并使用@LoadBalanced限定符. 警告 通过自动配置不再创建Re ...
- 使用RestTemplate访问restful服务时遇到的问题
可以通过通过wireshark抓包,使用Postman发送请求 wireshark是非常流行的网络封包分析软件,功能十分强大.可以截取各种网络封包,显示网络封包的详细信息.使用wireshark的人必 ...
- Spring Cloud入门教程 - Zuul实现API网关和请求过滤
简介 Zuul是Spring Cloud提供的api网关和过滤组件,它提供如下功能: 认证 过滤 压力测试 Canary测试 动态路由 服务迁移 负载均衡 安全 静态请求处理 动态流量管理 在本教程中 ...
随机推荐
- UILabel的各种属性和方法
转自:http://liulu200888an.blog.163.com/blog/static/3498972320121214208542/ UILabel *label1 = [[UILabe ...
- MES系统如何帮助烟草行业管理生产流程
与很多其他行业一样,烟草MES系统可以帮助卷烟企业实现智能生产.精益制造.快速实现烟草企业数字化车间的创建,助力企业实现改造升级,从而提升企业生产效率,降低生产成产.烟草行业得MES者得天下. 烟草行 ...
- cross validation交叉验证
交叉验证是一种检测model是否overfit的方法.最常用的cross validation是k-fold cross validation. 具体的方法是: 1.将数据平均分成k份,0,1,2,, ...
- liteos软件定时器(十)
1 概述 1.1 基本概念 软件定时器,是基于系统Tick时钟中断且由软件来模拟的定时器,当经过设定的Tick时钟计数值后会触发用户定义的回调函数.定时精度与系统Tick时钟的周期有关. 硬件定时器受 ...
- 《Linux就该这么学》课堂笔记01 linux初识
此书作者刘遄(Liu Chuán)从事于Linux运维技术行业,并且在2012年获得红帽工程师RHCE 6版本证书,在2015年初又分别获得红帽工程师RHCE 7版本证书与红帽架构师认证RHCA顶级证 ...
- linux下c语言实现多线程文件复制【转】
转自:https://www.cnblogs.com/zxl0715/articles/5365989.html .具体思路 把一个文件分成N份,分别用N个线程copy, 每个线程只读取指定长度字节大 ...
- 五、select的5种子句
1.Where 条件查询 比较运算符: 运算符 说明 > < = >= <= !=或<> In 在某集合内 between 在某范围内 In ...
- JPA-save()方法会将字段更新为null的解决方法
今天在开发上碰到一个问题,在做页面展示的时候传给前端十个字段,前端修改了其中3个的值,所以只传了3个值给后端,其余字段默认为null,更新后其他7个字段在全部变为了空值. 在前端没法全量回传所有属性的 ...
- 201871010109-胡欢欢 《面向对象程序设计(java)》第十五周学习总结
正文开头: 项目 内容 这个作业属于哪个课程 https://home.cnblogs.com/u/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwn ...
- day9_7.9 函数的定义
一.基础 1.什么是函数? 函数就是工具,方便开发人员开发软件,非常简洁的工具. 函数的关键字是def 在函数的编写阶段,只检验其语法是否正确,不检验代码. 在函数的调用阶段,可以通过函数名+()来调 ...