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介绍_java

虽然Spring的RestTemplate提供了对这么多HTTP method的支持,但是从个人工作角度来说,常用的也就get和post这两种方式,有兴趣的朋友可以自己翻看一下源码。

RestTemplate的使用

RestTemplate有两个构造方法,分别是:

public RestTemplate() {
          /**
               ...初始化过程
          */
}
 
public RestTemplate(ClientHttpRequestFactory requestFactory) { this(); setRequestFactory(requestFactory); } 
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> 
<!-- 配置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);
        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等参数。

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
   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");
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);
   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-templateshttps://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
	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);

以及:

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("。。。。"); }
   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("。。。。"); }

以及:

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); 
  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); 
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"); 

//delete方法(注意:delete方法没有返回值,说明,id=0这个参数在服务器端可以不定义该参数,直接使用request获取) 
// restTemplate.delete("http://localhost:8080/yongbarservice/appstore/appgoods/deleteranking?id=0");

参考资料:



 

1. Overview

In this tutorial, we’re going to illustrate the broad range of operations where the Spring REST Client – RestTemplate – can be used, and used well.

For the API side of all examples, we’ll be running the RESTful service from here.

Further reading:



Basic Authentication with the RestTemplate

How to do Basic Authentication with the Spring RestTemplate.

Read more →



RestTemplate with Digest Authentication

How to set up Digest Authentication for the Spring RestTemplate using HttpClient 4.

Read more →



HttpClient 4 Tutorial

Comprehensive Guide to the Apache HttpClient - start with basic usage and make your way though the advanced scenarios.

Read more →



2. Use GET to Retrieve Resources

2.1. Get Plain JSON

Let’s start simple and talk about GET requests – with a quick example using the getForEntity() API:




RestTemplate restTemplate =           new          RestTemplate();         


          String fooResourceUrl         


                    =           "http://localhost:8080/spring-rest/foos"          ;         


          ResponseEntity<String> response         


                    = restTemplate.getForEntity(fooResourceUrl +           "/1"          , String.          class          );         


          assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));



Notice that we have full access to the HTTP response – so we can do things like checking the status code to make sure the operation was actually successful, or work with the actual body of the response:



ObjectMapper mapper =           new          ObjectMapper();         


          JsonNode root = mapper.readTree(response.getBody());         


          JsonNode name = root.path(          "name"          );         


          assertThat(name.asText(), notNullValue());




We’re working with the response body as a standard String here – and using Jackson (and the JSON node structure that Jackson provides) to verify some details.

2.1. Retrieving POJO Instead of JSON

We can also map the response directly to a Resource DTO – for example:



public          class          Foo           implements          Serializable {         


                    private          long          id;         


                    


                    private          String name;         


                    // standard getters and setters         


          }




Now – we can simply use the getForObject API in the template:




Foo foo = restTemplate         


                    .getForObject(fooResourceUrl +           "/1"          , Foo.          class          );         


          assertThat(foo.getName(), notNullValue());         


          assertThat(foo.getId(), is(1L));



3. Use HEAD to Retrieve Headers

Let’s now have a quick look at using HEAD before moving on to the more common methods – we’re going to be using the headForHeaders() API here:



HttpHeaders httpHeaders = restTemplate         


                    .headForHeaders(fooResourceUrl);         


          assertTrue(httpHeaders.getContentType()         


                    .includes(MediaType.APPLICATION_JSON));




4. Use POST to Create a Resource

In order to create a new Resource in the API – we can make good use of the postForLocation()postForObject() or postForEntity() APIs.

The first returns the URI of the newly created Resource while the second returns the Resource itself.

4.1. The postForObject API




ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();         


          RestTemplate restTemplate =           new          RestTemplate(requestFactory);         


                    


          HttpEntity<Foo> request =           new          HttpEntity<>(          new          Foo(          "bar"          ));         


          Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.          class          );         


          assertThat(foo, notNullValue());         


          assertThat(foo.getName(), is(          "bar"          ));




4.2. The postForLocation API

Similarly, let’s have a look at the operation that – instead of returning the full Resource, just returns the Location of that newly created Resource:



HttpEntity<Foo> request =           new          HttpEntity<>(          new          Foo(          "bar"          ));         


          URI location = restTemplate         


                    .postForLocation(fooResourceUrl, request);         


          assertThat(location, notNullValue());




4.3. The exchange API

Finally, let’s have a look at how to do a POST with the more generic exchange API:



RestTemplate restTemplate =           new          RestTemplate();         


          HttpEntity<Foo> request =           new          HttpEntity<>(          new          Foo(          "bar"          ));         


          ResponseEntity<Foo> response = restTemplate         


                    .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.          class          );         


                    


          assertThat(response.getStatusCode(), is(HttpStatus.CREATED));         


                    


          Foo foo = response.getBody();         


                    


          assertThat(foo, notNullValue());         


          assertThat(foo.getName(), is(          "bar"          ));



5. Use OPTIONS to get Allowed Operations

Next, we’re going to have a quick look at using an OPTIONS request and exploring the allowed operations on a specific URI using this kind of request; the API is optionsForAllow:



Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);         


          HttpMethod[] supportedMethods         


                    = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE};         


          assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));



6. Use PUT to Update a Resource

Next, we’ll start looking at PUT – and more specifically the exchange API for this operation, because of the template.put API is pretty straightforward.

6.1. Simple PUT with .exchange

We’ll start with a simple PUT operation against the API – and keep in mind that the operation isn’t returning anybody back to the client:



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          );



6.2. PUT with .exchange and a Request Callback

Next, we’re going to be using a request callback to issue a PUT.

Let’s make sure we prepare the callback – where we can set all the headers we need as well as a request body:



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());         


                    };         


          }




Next, we create the Resource with POST request:



ResponseEntity<Foo> response = restTemplate         


                    .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.          class          );         


          assertThat(response.getStatusCode(), is(HttpStatus.CREATED));




And then we update the Resource:



Foo updatedInstance =           new          Foo(          "newName"          );         


          updatedInstance.setId(response.getBody().getId());         


          String resourceUrl =fooResourceUrl +           '/'          + response.getBody().getId();         


          restTemplate.execute(         


                    resourceUrl,          


                    HttpMethod.PUT,          


                    requestCallback(updatedInstance),          


                    clientHttpResponse ->           null          );




7. Use DELETE to Remove a Resource

To remove an existing Resource we’ll make short work of the delete() API:



String entityUrl = fooResourceUrl +           "/"          + existingResource.getId();         


          restTemplate.delete(entityUrl);




8. Configure Timeout

We can configure RestTemplate to time out by simply using ClientHttpRequestFactory – as follows:



RestTemplate restTemplate =           new          RestTemplate(getClientHttpRequestFactory());         


                    


          private          ClientHttpRequestFactory getClientHttpRequestFactory() {         


                    int          timeout =           5000          ;         


                    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory         


                    =           new          HttpComponentsClientHttpRequestFactory();         


                    clientHttpRequestFactory.setConnectTimeout(timeout);         


                    return          clientHttpRequestFactory;         


          }




And we can use HttpClient for further configuration options – as follows:


private          ClientHttpRequestFactory getClientHttpRequestFactory() {         


                    int          timeout =           5000          ;         


                    RequestConfig config = RequestConfig.custom()         


                    .setConnectTimeout(timeout)         


                    .setConnectionRequestTimeout(timeout)         


                    .setSocketTimeout(timeout)         


                    .build();         


                    CloseableHttpClient client = HttpClientBuilder         


                    .create()         


                    .setDefaultRequestConfig(config)         


                    .build();         


                    return          new          HttpComponentsClientHttpRequestFactory(client);         


          }




9. Conclusion

We went over the main HTTP Verbs, using RestTemplate to orchestrate requests using all of these.

If you want to dig into how to do authentication with the template – check out my write-up on Basic Auth with RestTemplate.

The implementation of all these examples and code snippets can be found in my GitHub project

 

http://www.baeldung.com/rest-template