[Calling Third-party API - Spring RestTemplate] The Guide to RestTemplate
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others...
Posted by Mr.Vincent on
2020-11-12
Estimated Reading Time 22 Minutes
Words 4.2k In Total
Viewed Times
首先在我们学习使用 RestTemplate 之前,先认识下这个类,来看 Spring 官方怎么描述的。 从官方 API 文档 RestTemplate javadoc 可以找该类的描述如下:
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others.
The RestTemplate offers templates for common scenarios by HTTP method, in addition to the generalized exchange and execute methods that support of less frequent cases.
接下来我们看下 RestTemplate 类提供的 API 有哪些,RestTemplate 提供了将近 30 个请求方法,其中多数是单个方法重载实现,这里主要参考官方文档 rest-resttemplate 进行如下分类:
Table 1. RestTemplate methods
Method group
Description
getForObject
Retrieves a representation via GET.
getForEntity
Retrieves a ResponseEntity (that is, status, headers, and body) by using GET.
headForHeaders
Retrieves all headers for a resource by using HEAD.
postForLocation
Creates a new resource by using POST and returns the Location header from the response.
postForObject
Creates a new resource by using POST and returns the representation from the response.
postForEntity
Creates a new resource by using POST and returns the representation from the response.
put
Creates or updates a resource by using PUT.
patchForObject
Updates a resource by using PATCH and returns the representation from the response.
Note that the JDK HttpURLConnection does not support the PATCH, but Apache
HttpComponents and others do.
delete
Deletes the resources at the specified URI by using DELETE.
optionsForAllow
Retrieves allowed HTTP methods for a resource by using ALLOW.
exchange
More generalized (and less opinionated) version of the preceding methods that provides extra
flexibility when needed. It accepts a RequestEntity (including HTTP method, URL, headers,
and body as input) and returns a ResponseEntity.
These methods allow the use of ParameterizedTypeReference instead of Class to specify
a response type with generics.
execute
The most generalized way to perform a request, with full control over request
preparation and response extraction through callback interfaces.
@Bean public RestTemplate restTemplate(){ var factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(3000); factory.setReadTimeout(3000); returnnew RestTemplate(factory); }
Using Apache HTTPClient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
@Autowired CloseableHttpClient httpClient; @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory()); return restTemplate; } @Bean public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory(){ HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setHttpClient(httpClient); return clientHttpRequestFactory; }
最后依赖注入就可以了。
1 2
@Autowired private RestTemplate restTemplate;
RestTemplate Example
HTTP GET Example
HTTP GET REST APIs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * @author vincent */ @RequestMapping(value = "/product") @RestController publicclassProductController{
@GetMapping("/getProductByNoParams") public Product getProductByNoParams(){ returnnew Product(1, "ProductA", BigDecimal.valueOf(6666.0), new Date()); }
@GetMapping("/getProductById") public Product getProductById(Integer id){ returnnew Product(id, "ProductC", BigDecimal.valueOf(6666.0), new Date()); } }
@PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file)throws IOException { String name = file.getOriginalFilename(); System.out.println(String.format("File name: %s", name));
//todo save to a file via multipartFile.getInputStream() byte[] bytes = file.getBytes(); System.out.println(String.format("File uploaded content:\n%s", new String(bytes))); return"file uploaded"; }
An HttpMessageConverter implementation that can read and write String instances from the HTTP
request and response. By default, this converter supports all text media types
(text/*) and writes with a Content-Type of text/plain.
FormHttpMessageConverter
An HttpMessageConverter implementation that can read and write form data from the HTTP
request and response. By default, this converter reads and writes the
application/x-www-form-urlencoded media type. Form data is read from and written into a
MultiValueMap<String, String>. The converter can also write (but not read) multipart
data read from a MultiValueMap<String, Object>. By default, multipart/form-data is
supported. As of Spring Framework 5.2, additional multipart subtypes can be supported for
writing form data. Consult the javadoc for FormHttpMessageConverter for further details.
ByteArrayHttpMessageConverter
An HttpMessageConverter implementation that can read and write byte arrays from the
HTTP request and response. By default, this converter supports all media types (*/*)
and writes with a Content-Type of application/octet-stream. You can override this
by setting the supportedMediaTypes property and overriding getContentType(byte[]).
MarshallingHttpMessageConverter
An HttpMessageConverter implementation that can read and write XML by using Spring’s
Marshaller and Unmarshaller abstractions from the org.springframework.oxm package.
This converter requires a Marshaller and Unmarshaller before it can be used. You can inject these
through constructor or bean properties. By default, this converter supports
text/xml and application/xml.
MappingJackson2HttpMessageConverter
An HttpMessageConverter implementation that can read and write JSON by using Jackson’s
ObjectMapper. You can customize JSON mapping as needed through the use of Jackson’s
provided annotations. When you need further control (for cases where custom JSON
serializers/deserializers need to be provided for specific types), you can inject a custom ObjectMapper
through the ObjectMapper property. By default, this
converter supports application/json.
MappingJackson2XmlHttpMessageConverter
An HttpMessageConverter implementation that can read and write XML by using
Jackson XML extension’s
XmlMapper. You can customize XML mapping as needed through the use of JAXB
or Jackson’s provided annotations. When you need further control (for cases where custom XML
serializers/deserializers need to be provided for specific types), you can inject a custom XmlMapper
through the ObjectMapper property. By default, this
converter supports application/xml.
SourceHttpMessageConverter
An HttpMessageConverter implementation that can read and write
javax.xml.transform.Source from the HTTP request and response. Only DOMSource,
SAXSource, and StreamSource are supported. By default, this converter supports
text/xml and application/xml.
BufferedImageHttpMessageConverter
An HttpMessageConverter implementation that can read and write
java.awt.image.BufferedImage from the HTTP request and response. This converter reads
and writes the media type supported by the Java I/O API.
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !