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("acce