RestTemplate实践

一、RestTemplate是什么

环境约束:

spring-web-4.3.9.RELEASE

Spring文档: https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/remoting.html#rest-client-access

The RestTemplate is the core class for client-side access to RESTful services. It is conceptually similar to other template classes in Spring, such as JdbcTemplate andJmsTemplate and other template classes found in other Spring portfolio projects.RestTemplate’s behavior is customized by providing callback methods and configuring the HttpMessageConverter used to marshal objects into the HTTP request body and to unmarshal any response back into an object. As it is common to use XML as a message format, Spring provides a MarshallingHttpMessageConverter that uses the Object-to-XML framework that is part of the org.springframework.oxm package. This gives you a wide range of choices of XML to Object mapping technologies to choose from.

This section describes how to use the RestTemplate and its associated HttpMessageConverters.

RestTemplate是Spring的通过客户端访问RESTful服务端的核心类,和JdbcTemplate、JmsTemplate概念相似,都是Spring提供的模板类

RestTemplate的行为可以通过callback回调方法和配置HttpMessageConverter 来定制,用来把对象封装到HTTP请求体,将响应信息放到一个对象中

Invoking RESTful services in Java is typically done using a helper class such as Apache HttpComponents HttpClient. For common REST operations this approach is too low level as shown below.

java中调用RESTful服务很典型的是使用HttpClient,对于常用的REST操作,这些方法属于低等级的操作

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

使用HttpClient我们需要自己封装Post请求,再根据响应的状态码判断从响应中获取header和body,有时候还需要自己做json转换

RestTemplate provides higher level methods that correspond to each of the six main HTTP methods that make invoking many RESTful services a one-liner and enforce REST best practices.

RestTemplate提供更高等级的符合HTTP的6中主要方法,可以很简单的调用RESTful服务

二、创建RestTemplate

创建RestTemplate很简单,只需要new RestTemplate(),如果使用Spring架构,将创建的RestTemplate实例通过XML或注解的方式注册到Spring容器中即可

举例:

@Bean public RestTemplate restTemplate() { return new RestTemplate(); } RestTemplate构造方法

RestTemplate有3个构造方法,一个无参构造,两个有参构造

RestTemplate无参构造

/** * Create a new instance of the {@link RestTemplate} using default settings. * Default {@link HttpMessageConverter}s are initialized. * 使用默认配置创建一个RestTemplate实例 * 默认的HttpMessageConverter集合被初始化 */ public RestTemplate() { this.messageConverters.add(new ByteArrayHttpMessageConverter()); this.messageConverters.add(new StringHttpMessageConverter()); this.messageConverters.add(new ResourceHttpMessageConverter()); this.messageConverters.add(new SourceHttpMessageConverter<Source>()); this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); if (romePresent) { this.messageConverters.add(new AtomFeedHttpMessageConverter()); this.messageConverters.add(new RssChannelHttpMessageConverter()); } if (jackson2XmlPresent) { this.messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); } else if (jaxb2Present) { this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); } /** * 如果类路径下包含com.fasterxml.jackson.databind.ObjectMapper 和 com.fasterxml.jackson.core.JsonGenerator * 使用jackson做http请求、响应的json转换 */ if (jackson2Present) { this.messageConverters.add(new MappingJackson2HttpMessageConverter()); } else if (gsonPresent) { this.messageConverters.add(new GsonHttpMessageConverter()); } }

参数为ClientHttpRequestFactory的构造

/** * Create a new instance of the {@link RestTemplate} based on the given {@link ClientHttpRequestFactory}. * @param requestFactory HTTP request factory to use * @see org.springframework.http.client.SimpleClientHttpRequestFactory * @see org.springframework.http.client.HttpComponentsClientHttpRequestFactory * 使用指定的ClientHttpRequestFactory创建一个RestTemplate实例 * requestFactory是用于创建HTTP请求的工厂,默认的实现有 * SimpleClientHttpRequestFactory、HttpComponentsClientHttpRequestFactory * 如果没有设置默认是SimpleClientHttpRequestFactory */ public RestTemplate(ClientHttpRequestFactory requestFactory) { this(); //也会调用无参构造初始化默认的messageConverters setRequestFactory(requestFactory); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwyjgd.html