`

Spring RestTemplate介绍

 
阅读更多

http://www.cnblogs.com/softidea/p/5977375.html

 

http://www.cnblogs.com/rollenholt/p/3894117.html

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等参数。

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

我一般常用的方法为:

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

以及:

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

参考资料:

http://www.cnblogs.com/fx2008/p/4010875.html

 

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:

1
2
3
4
5
6
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl
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:

1
2
3
4
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:

1
2
3
4
5
6
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:

1
2
3
4
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:

1
2
3
4
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

1
2
3
4
5
6
7
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:

1
2
3
4
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:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
4
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:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
ResponseEntity<Foo> response = restTemplate
  .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));

And then we update the Resource:

1
2
3
4
5
6
7
8
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:

1
2
String entityUrl = fooResourceUrl + "/" + existingResource.getId();
restTemplate.delete(entityUrl);

8. Configure Timeout

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

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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 – this is a Maven-based project, so it should be easy to import and run as it is.

 

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

分享到:
评论

相关推荐

    springRestTemplate

    在 Spring Boot 中,由于其内置的自动配置特性,使用 RestTemplate 更加方便。让我们深入探讨一下 RestTemplate 的核心概念、功能以及如何在实际应用中进行设置和使用。 1. **什么是 RestTemplate?** RestTemplate...

    Spring RestTemplate

    Spring 3.0 RestTemplate

    RestTemplate如何在Spring或非Spring环境下使用.docx

    在非Spring环境下,可以直接引用`spring-web`模块来使用`RestTemplate`,无需整个Spring框架。只需在Maven或Gradle的依赖管理中添加`spring-web`,然后实例化`RestTemplate`对象即可进行HTTP请求。 然而,随着...

    Spring RestTemplate基本使用介绍

    Spring RestTemplate 基本使用介绍 Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,提供了多种便捷访问远程 HTTP 服务的方法,能够大大提高客户端的编写效率。下面我们将详细介绍 Spring ...

    SpringRestTemplate的一个客户端响应路由

    `Riptide`是由Zalando公司开发的一个库,它是对Spring`RestTemplate`的增强,特别关注于提高客户端的响应路由能力。响应路由允许我们在收到服务器响应后进行灵活的处理,比如根据不同的响应状态码或内容类型采取不同...

    Spring RestTemplate Http 工具类,支持 HTTP、HTTPS

    工作中常用的远程调用请求工具类,支持请求方法:GET、POST、PUT、DELETE,支持媒体格式:text/plain、text/xml、application/json、application/x-www-form-urlencoded,支持请求协议:HTTP、HTTPS,该工具类直接可...

    如何使用Spring RestTemplate访问restful服务

    "使用Spring RestTemplate访问restful服务" Spring RestTemplate是Spring框架中的一种轻量级客户端,用于访问restful服务。它提供了一种简洁的方式来访问restful接口,简化了HTTP请求和响应处理的过程。 什么是...

    Spring RestTemplate具体使用详解

    Spring RestTemplate具体使用详解 RestTemplate是Spring框架中的一种ynchronous客户端HTTP访问的核心类,简化了与HTTP服务器的通信,并强制实施RESTful原则。它处理HTTP连接,让应用程序代码提供URL(可能具有模板...

    《深入理解Spring Cloud与微服务构建》学习笔记(十一)~使用RestTemplate和Ribbo消费服务

    总结,本篇学习笔记主要介绍了Spring Cloud中使用RestTemplate和Ribbon进行服务消费的方法,包括RestTemplate的使用、Ribbon的客户端负载均衡原理以及如何在实际代码中实现这些功能。这为我们构建高可用、松耦合的...

    spring-etcd:基于Spring RestTemplate的etcd v2客户端

    本项目"spring-etcd"则是将这两者结合,提供了一个基于Spring RestTemplate的Etcd v2客户端,使得Java开发者可以更方便地与Etcd进行交互。 首先,我们来理解Spring RestTemplate。RestTemplate是Spring提供的一个...

    Spring使用RestTemplate模拟form提交示例

    在本文中,我们将介绍如何使用 Spring 的 RestTemplate 来模拟 Form 提交的示例。RestTemplate 是 Spring 框架中的一种模板类,用于在客户端访问 Web 服务。通过提供回调方法和配置 HttpMessageConverter 类,可以对...

    spring rest mvc使用RestTemplate调用

    在Spring应用中,可以通过`RestTemplate`的默认构造函数来实例化,或者在配置类中通过@Bean注解声明一个实例,以便进行依赖注入。例如: ```java @Bean public RestTemplate restTemplate() { return new ...

    SpringCloud简单使用RestTemplate调用对方的服务

    在这个场景下,我们将关注如何使用Spring Cloud中的`RestTemplate`来调用其他服务。`RestTemplate`是Spring提供的一种HTTP客户端工具,用于发送HTTP请求并处理响应。 首先,让我们了解Spring Cloud的核心组件之一...

    微服务springcloud:eureka整合gateway、RestTemplate和FeignClient

    本主题将深入探讨如何在Spring Cloud中整合Eureka、Gateway、RestTemplate和FeignClient,以实现高效且可靠的微服务通信。 首先,Eureka是Spring Cloud中的一个关键组件,它是一个服务注册与发现的工具。Eureka ...

    Spring boot,springCloud精选视频教程

    6.Spring RestTemplate中几种常见的请求方式 7.RestTemplate的逆袭之路,从发送请求到负载均衡 8.Spring Cloud中负载均衡器概览 9.Spring Cloud中的负载均衡策略 10.Spring Cloud中的断路器Hystrix 11.Spring ...

    Spring cloud restTemplate 传递复杂参数的方式(多个对象)

    在这篇文章中,我们主要介绍了 Spring Cloud RestTemplate 传递复杂参数的方式(多个对象)。 在实际开发中,我们经常遇到这样的问题:服务 A 需要调用服务 B,并传递多个参数。在这种情况下,我们可以使用 ...

    RestTemplate实现服务间调用demo案例

    Spring Cloud为了解决这个问题,提供了一种简单易用的工具——RestTemplate。本示例将详细解析如何利用RestTemplate进行服务间的调用,帮助开发者理解并实践相关知识。 首先,我们要知道什么是RestTemplate。...

    RestTemplate请求失败自动重试机制.docx

    本节我们将探讨如何利用Spring Retry库来实现RestTemplate的自动重试机制。 首先,为了启用Spring Retry,我们需要在项目中引入相应的依赖。添加`spring-retry`和`aspectjweaver`的Maven坐标: ```xml &lt;groupId&gt;...

    Springboot RestTemplate 简单使用解析

    本文主要介绍了 Springboot RestTemplate 的简单使用解析,通过示例代码对 RestTemplateUtil 类的使用进行了详细的介绍。该类可以帮助开发者快速地调用 RESTful 服务,提高开发效率和可维护性。

Global site tag (gtag.js) - Google Analytics