1. RestTemplate介绍
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()等方法。
Spring’scentral class for synchronous client-side HTTP access.It
simplifies communication with HTTPservers, and enforces RESTful
principles. Ithandles HTTP connections, leaving application code to
provide URLs(with possible template variables) andextract results.简单说就是:简化了发起HTTP请求以及处理响应的过程,并且支持REST。为什么说简化了呢?
来看HttpClient和RestTemplate访问url的实现方式
(1)使用java.net包下的URLConnection建立连接
String result= "";
BufferedReaderin = null;
try {
String urlNameString= url +"?" + param;
URL realUrl= new URL(urlNameString);
// 打开和URL之间的连接
URLConnectionconnection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String,List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for(String key : map.keySet()) {
System.out.println(key+ "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in =new BufferedReader(newInputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine())!= null) {
result += line;
}
} catch (Exception e) {
…
}
// 使用finally块来关闭输入流
finally{
// 关闭流
}
(2)使用RestTempalte
ResponseEntity<SsoUrlPrm> result=restTemplate.getForEntity(requestPathUrl,SsoUrlPrm.class);
简单来说RestTemplate就是通过封装一系列Http的请求,然后暴露给用户一个非常简单易用的Http访问的方法。
2. RestTemplate方法介绍

3.通过RestTemplate调用微服务
(1) 在 Eureka客户端中的启动类 中配置RestTemplate
@SpringBootApplication
@EntityScan("cn.itcast.order.entity")
public class OrderApplication {
/**
* 使用spring提供的RestTemplate发送http请求到商品服务
* 1.创建RestTemplate对象交给容器管理
* 2.在使用的时候,调用其方法完成操作 (getXX,postxxx)
* *
*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
}
(2)编写Controller调用服务
@RestController
@RequestMapping("/order")
public class OrderController {
//注入restTemplate对象
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable Long id) {
Product product = null;
//restTemplate.getForObject("",Product.class);
product = restTemplate.getForObject("http://127.0.1:9011/product/1",Product.class);
return product;
}
}
Spring的RestTemplate类简化了与HTTP服务的通信,提供了统一的RESTful调用方式,支持GET、POST等HTTP方法。它比HttpClient更优雅,可以通过setRequestFactory更换HTTP库。本文将介绍RestTemplate的介绍、方法以及如何通过它调用微服务。
1159

被折叠的 条评论
为什么被折叠?



