RestTemplate
这篇文章打算介绍一下Spring的RestTemplate
。我这边以前设计到http交互的,之前一直采用的是Apache HttpComponents
。后来发现Spring框架中已经为我们封装好了这个框架。因此我们就不需要直接使用下面这种稍微底层一点的方式来实现我们的功能:
String uri = "http://example.com/hotels/1/bookings"; PostMethod post = new PostMethod(uri); String request = // create booking request content post.setRequestEntity(new StringRequestEntity(request)); httpClient.executeMethod(post); if (HttpStatus.SC_CREATED == post.getStatusCode()) { Header location = post.getRequestHeader("Location"); if (location != null) { System.out.println("Created new booking at :" + location.getValue()); } }
Spring的RestTemplate提供了一些更高级别的方法来满足我们的功能,比如对HTTP Method的支持:
虽然Spring的RestTemplate提供了对这么多HTTP method的支持,但是从个人工作角度来说,常用的也就get和post这两种方式,有兴趣的朋友可以自己翻看一下源码。
RestTemplate的使用
RestTemplate有两个构造方法,分别是:
public RestTemplate() { /** ...初始化过程 */ } public RestTemplate(ClientHttpRequestFactory requestFactory) { this(); setRequestFactory(requestFactory); }
其中,第二个构造方法中可以传入ClientHttpRequestFactory参数,第一个进行默认初始化,因为我们经常需要对请求超时进行设 置并能够对超时进行后续处理,而第一个构造方法,我们无法控制超时时间,第二个构造中的ClientHttpRequestFactory接口的实现类中 存在timeout属性,因此选用第二个构造方法。
在spring配置文件中进行如下配置:
<!-- 配置RestTemplate --> <!--Http client Factory--> <bean id="httpClientFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory"> <property name="connectTimeout" value="${connectTimeout}"/> <property name="readTimeout" value="${readTimeout}"/> </bean> <!--RestTemplate--> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="httpClientFactory"/> </bean>
当然也可以直接使用:
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(1000); requestFactory.setReadTimeout(1000); RestTemplate restTemplate = new RestTemplate(requestFactory);
注意:ClientHttpRequestFactory 接口有4个实现类,分别是:
- AbstractClientHttpRequestFactoryWrapper 用来装配其他request factory的抽象类。
- CommonsClientHttpRequestFactory 允许用户配置带有认证和http连接池的httpclient,已废弃,推荐用HttpComponentsClientHttpRequestFactory。
- HttpComponentsClientHttpRequestFactory 同2.
- SimpleClientHttpRequestFactory 接口的一个简单实现,可配置proxy,connectTimeout,readTimeout等参数。
配置使用带有连接池的httpclient
<bean id="clientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"> <constructor-arg> <bean class="org.apache.http.impl.client.DefaultHttpClient"> <constructor-arg> <bean class="org.apache.http.impl.conn.PoolingClientConnectionManager"> <property name="maxTotal" value="10" /> <property name="defaultMaxPerRoute" value="5" /> </bean> </constructor-arg> </bean> </constructor-arg> <property name="connectTimeout" value="30000" /> <property name="readTimeout" value="30000" /> </bean> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="clientHttpRequestFactory" /> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" /> <bean class="org.springframework.http.converter.FormHttpMessageConverter" /> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter" /> </list> </property> </bean>
GET
Spring的RestTemplate提供了许多的支持,这里仅仅列出常用的接口:
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> urlVariables) throws RestClientException
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException
对于GET请求来说,我一般常用的几种形式如下:
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class,"42", "21");
或者下面这张形式:
Map<String, String> vars = Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);
以及:java String message = restTemplate.getForObject("http://localhost:8080/yongbarservice/appstore/appgoods/restTemplate?name=zhaoshijie&id=80", String.class );
他这种做法参考了uri-templates
(https://code.google.com/p/uri-templates/)这个项目。
POST
Spring的RestTemplate对post的常用接口:
public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException
public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException
public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException
我一般常用的方法为:
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<String, String>(); bodyMap.setAll(urlVariables); ResponseClass responseClass = restTemplate.postForObject(CAR_CES_URL, bodyMap, ResponseClass.class);
这种用法适用于 org.springframework.http.converter.FormHttpMessageConverter
以及:
HttpHeaders headers = new HttpHeaders();
headers.add("X-Auth-Token", "e348bc22-5efa-4299-9142-529f07a18ac9");
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("owner", "11");
postParameters.add("subdomain", "aoa");
postParameters.add("comment", "");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);
ParseResultVo exchange = null;
try {
exchange = restTemplate.postForObject("http://l-dnsutil1.ops.beta.cn6.qunar.com:10085/v1/cnames/tts.piao", requestEntity, ParseResultVo.class);
logger.info(exchange.toString());
} catch (RestClientException e) {
logger.info("。。。。");
这样可以指定Headers的参数,因为http1.1默认Header中的Connection 为Keep-Alive的,可以通过这种方法将其修改。
以及:
DomainParam domainParam = new DomainParam();
domainParam.setCustomerId(1);
//...
logger.info("....");
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
String responseResult = restTemplate.postForObject(url, domainParam, String.class);
其他
PUT
方式:
restTemplate.put("http://localhost:8080/yongbarservice/appstore/appgoods/restTemplate?name=zhaoshijie&id=80" ,null);
DELETE
方式
//delete方法(注意:delete方法没有返回值,说明,id=0这个参数在服务器端可以不定义该参数,直接使用request获取)
// restTemplate.delete("http://localhost:8080/yongbarservice/appstore/appgoods/deleteranking?id=0");
参考资料:
相关推荐
RestTemplate可以发送HTTP GET请求,经常使用到的方法有两个: getForObject() getForEntity() 二者的主要区别在于,getForObject()返回值是HTTP协议的响应体。getForEntity()返回的是ResponseEntity,Response...
SpringBoot系列之RestTemplate使用示例,博主之前经常对接一些接口,所以发现写一些http请求比较麻烦,学习springboot的过程知道可以用 RestTemplate来做http请求,RestTemplate 是 Spring Framework 框架封装的基于...
RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。也就是说RestTemplate是一个封装,底层...
其实POST请求方法和GET请求方法上大同小异,RestTemplate的POST请求也包含两个主要方法: postForObject() postForEntity() 二者的主要区别在于,postForObject()返回值是HTTP协议的响应体。postForEntity()返回...
7、RestTemplate 用法详解 8、 服务请求负载均衡 9、声明式服务调用 Feign 10、Feign 中的继承、日志与数据压缩 11、Resilience4j 基本用法详解 12、Resilience4j 在微服务中的应用 13、Micrometer 实现微服务监控 ...
下面小编就为大家带来一篇基于RestTemplate的使用方法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
文章首先介绍了RestTemplate和WebClient的基本概念和原理,然后详细介绍了它们的配置和使用方法。通过实例演示了如何使用这两种客户端发送HTTP请求和接收响应。最后,文章对RestTemplate和WebClient的优缺点进行了...
java中使用restTemplate发送http请求,内涵post和get方法,单例模式,开箱即用
基于springboot的RestTemplate、okhttp和HttpClient对比 ...2、RestTemplate: 是 Spring 提供的用于访问Rest服务的客户端, RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
主要给大家介绍了关于Spring学习笔记之RestTemplate使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Rest Client Builder ... 构造和使用REST“动词”之一。 GET请求: def resp = rest.get("http://grails.org/api/v1.0/plugin/acegi/") 响应是一个Spring 。 有一些获取JSON的便捷方法: resp.json instanceof
JAVA SpringBoot环境 使用RestTemplate POST方法传递JSON字符串 GET方法,通过路径传参 POST方法传递form表单 GET方法无参
SpringCloud简单小项目 -- ## 使用微服务 1. 创建一个空项目进行管理 2. 创建子项目 3. 创建一个公共访问的...//远程调用 通过RestTemplate 的方法来调用其他项目数据 RestTemplate template = new RestTemplate();
货币兑换服务 该项目是一个测试微服务项目,用于测试对另一个名为currency-exchange-service的...1-RestTemplate 2-Feign 3-Ribbon 4-命名服务器客户端5-Zuul api网关6-使用Spring Cloud sleuth将唯一的ID添加到日志7-
RestTemplate使用示例Demo,一共包括三个服务:公共API服务、提供者服务、消费者服务。其中示例了服务之间的相互调用和两个方法示例。分别为新增数据和查询方法示例。有兴趣的可以自行下载学习。
RestTemplate作为spring-web项目的一部分,在Spring3.0版本开始被引入。根据Spring官方文档及源码中的介绍,RestTemplate在将来的版本中它可能会被弃用, 作为替代,Spring官方已在Spring 5中引入了WebClient作为非...
使用RestTemplate调用远程服务时就像本地服务调用一样简单使用方法:deploy到自己的仓库在pom.xml里加入引用在启动类加上@EnableRestClient调用远程api直接定义接口,在接口上添加注解@RestClient(配置远程服务)声明...
通过多线程处理大批量耗时业务,并返回结果。当监测到线程池中存在空闲线程时则动态向线程池中添加新的任务,直到所有任务执行结束。Demo为自己写的测试使用,下载后可直接运行测试。
结合restTemplate可实现负载均衡用法:1.类加注解@EnableDiscoveryClient2.负载均衡的restTemplate@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}3.调用:public String
应用间通信 ...Dubbo (RPC) 1.SpringCloud中服务间两种restful调用方式 RestTemplate Feign 方式一、RestTemplate:是一个...使用 restTemplate.getForObject("http://localhost:8080/msg", String.class);方法