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 的 getForEntity 方法来执行 GET 请求,并将结果返回为 String 类型。 POST-JSON 请求 POST-JSON 请求用于发送 JSON 数据到服务端。RestTemplateUtil 中的 PostJsonData 方法提供了 POST-...
在Java Spring框架中,`RestTemplate` 是一个强大的...理解并熟练使用`RestTemplate` 的各种方法和特性,能显著提高开发效率,简化HTTP客户端的实现。希望本文提供的信息能对你在使用`RestTemplate` 的过程中有所帮助。
SpringBoot系列之RestTemplate使用示例,博主之前经常对接一些接口,所以发现写一些http请求比较麻烦,学习springboot的过程知道可以用 RestTemplate来做http请求,RestTemplate 是 Spring Framework 框架封装的基于...
为了演示 RestTemplate 的使用,我们创建两个 Spring Boot 项目,一个 provider 作为 server 端,一个 consumer 作为服务调用方法。 API 方法介绍 RestTemplate 提供了多种 API 方法来访问远程 HTTP 服务,下面...
在使用RestTemplate时,可以使用多种方式来实现HTTP请求,例如使用getForObject()方法来获取资源,使用postForObject()方法来添加新的内容等。同时,RestTemplate也提供了异常处理机制,可以捕获和处理HTTP请求过程...
然而,有时我们可能需要在不使用 Feign 注解的情况下,利用 RestTemplate 来实现类似的功能。本文将深入探讨如何使用 RestTemplate 进行 FeignClient 调用。 首先,让我们了解什么是 RestTemplate。RestTemplate 是...
3. **构建请求**:使用RestTemplate的`exchange()`、`getForObject()`、`postForEntity()`等方法构造请求。例如,调用服务A的`/api/user`接口获取用户信息: ```java ResponseEntity<UserInfo> response = ...
最后,我们使用 RestTemplate 的 postForObject 方法来提交请求。 总结 在本文中,我们介绍了如何使用 Spring 的 RestTemplate 来模拟 Form 提交的示例。RestTemplate 提供了多种方法来执行 HTTP 请求,并且可以对...
- **使用占位符传参**:`getForObject()`支持使用占位符,例如`restTemplate.getForObject(url, PostDTO.class, "posts", 1)`,这样可以根据业务需求动态构造URL。 4. JSONPlaceholder作为测试工具 ...
SpringMVC中RestTemplate传值接值方法是指在SpringMVC框架中使用RestTemplate来进行数据传输和接收的一种方法。这种方法可以帮助开发者快速简便地实现数据交换和处理。 RestTemplate的配置 在使用RestTemplate之前...