In the previous article introducing Eureka service, we introduced the scenario where a consumer obtains the server address information from Eureka through LoadBalancerClient and invokes the service remotely through RestTemplate. This article specifically introduces the use of RestTemplate

RestTemplate

SpringRestTemplate is a client provided by Spring for accessing Rest services. RestTemplate provides a variety of convenient methods for accessing remote Http services. It can greatly improve the client writing efficiency, so many clients such as Android and third-party service providers use RestTemplate to request restful services

1. Environment construction

To demonstrate the use of the RestTemplate, we create two SpringBoot projects, one provider for the server side and one Consumer for the service invocation method

2.API method introduction

API instructions
getForEntity() Send an HTTP GET request that returns ResponseEntity containing the object mapped to the response body
getForObject() Send an HTTP GET request, and the returned request body is mapped to an object
postForEntity() POST data to a URL that returns a ResponseEntity containing an object mapped from the response body
postForObject() POST data to a URL that returns an object based on the response body match
headForHeaders() Send an HTTP HEAD request that returns an HTTP header containing the URL of a particular resource
optionsForAllow() Send an HTTP OPTIONS request that returns the Allow header for a specific URL
postForLocation() POST data to a URL that returns the URL of the newly created resource
put() PUT a resource to a specific URL
delete() Perform an HTTP DELETE operation on a resource at a specific URL
exchange() A specific HTTP method is executed on the URL to return the ResponseEntity containing the object mapped from the response body
execute() Executes a specific HTTP method on the URL that returns an object mapped from the response body

3. Specific use

Let’s take a look at the effects of four common HTTP requests

3.1 No-parameter Request

Let’s take a look at the server request method that doesn’t need to receive arguments,

getForEntity

The server side is implemented through getForEntity

@return */ @getMapping ("/server1") Public String server1String(){system.out.println (" The server is accessed... ); return "success"; }Copy the code

call

/** * RestTemplate accesses the first service of the provider server1 */ @test public void contextLoads() {String url = "http://localhost:8080/server1"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class); // Get the status of the response HttpStatus statusCode = entity.getStatusCode(); HttpHeaders headers = entity.getheaders (); String MSG = entity.getBody(); System.out.println(statusCode); System.out.println(headers); System.out.println(msg); }Copy the code

The output

Description:

1. GetForEntity execute () method returns the type is ResponseEntity, ResponseEntity is Spring encapsulation of the HTTP request and response, including several important elements, For example, response code, contentType, contentLength, response message body, etc. In the output result, we can see that 2. GetForEntity () parameter, the first is the request address, and the second is the type corresponding to T

getForObject

The getForObject function is actually a further encapsulation of getForEntity. You can use getForObject if you only care about the content of the returned message body and nothing else

/ * * * * / @ getForObject visit Test public void contextLoadsObject () {String url = "http://localhost:8080/server1"; RestTemplate restTemplate = new RestTemplate(); / / direct return is the result we need, but can't get the corresponding response status information such as the String MSG = restTemplate. GetForObject (url String. The class). System.out.println(msg); }Copy the code

3.2 Parameter Request

Server-side methods need to receive arguments passed by the caller

/** ** Basic Data Type Mandatory String * @return */ @requestMapping ("/server2") Public String server2String(Integer ID,String userName){ System.out.println(" The server is accessed...") +id+" "+userName); Return "success "; } /** ** Basic Data Type Returned String * @return */ @requestMapping ("/server3") Public String server3String(User User){ System.out.println(" The server is accessed...") +user); Return "success "; }Copy the code

getForEntity

The caller can call in two ways: first with a numeric placeholder, and finally with a variable length argument, to replace the previous placeholder

/ * * * request service basic data type and passing parameters * * / @ Test public void testServer2 () {/ / parameter in the url String after the url = "http://localhost:8080/server2? id={1}&userName={2}"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class,5,"bobo"); System.out.println(entity.getBody()); }Copy the code

The second way is to use the form name={name}, the last parameter is a map, map key is the name of the placeholder, map value is the parameter value

/ * * * request service basic data type and passing parameters * * / @ Test public void testServer3 () {String url = "http://localhost:8080/server2? id={id}&userName={userName}"; Map<String,Object> map = new HashMap<>(); map.put("id",6); Map. put("userName"," bobo roast duck "); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class,map); System.out.println(entity.getBody()); }Copy the code

postForEntity

If the request is submitted via post, we can use the following server parameters: note the @requestBody annotation

/** ** Basic data type Return String * @return */ @requestMapping ("/server3") public String server3String(@requestBody User User){ System.out.println(" The server is accessed...") +user); Return "success "; }Copy the code

The client

/** * postForEntity(url,user, string.class) * url: request address * user: request data * string.class Type of data to receive return */ @test public void contextLoadsObject1() { String url = "http://localhost:8080/server3"; RestTemplate restTemplate = new RestTemplate(); User User = new User(1,"bobo","中国"); / / direct return is the result we need, but can't get the corresponding response status information such as the String MSG = restTemplate. PostForEntity (url, user, String. The class). GetBody (); System.out.println(msg); }Copy the code

3.3 Returning its own type

Data of our custom type returned by the server

@requestMapping ("/server4") public User server4Object(){system.out.println (" server is accessed... ); Return new User(2," li si "," Shenzhen "); }Copy the code

Client:

/ * * * return type for a custom type * / @ Test public void testServer5 () {String url = "http://localhost:8080/server4"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<User> entity = restTemplate.getForEntity(url, User.class); System.out.println(entity.getBody()); }Copy the code

Use getForEntity and getForObject and postForEntity and postForObject are pretty much the same, just pay attention to the type that you receive.

3.4 Returned list with generic scenarios

Here we need to use the Exchange method, specifically as follows

  1. Methods that allow callers to specify HTTP requests (GET,POST,PUT, etc.)
  2. You can add body and header information to the request using the ‘HttpEntity
    requestEntity ‘description
  3. Exchange support ‘type containing parameters (i.e., a generic class) as a return type, the feature by’ ParameterizedTypeReferenceresponseType ‘description
@requestMapping ("/server5") public List<User> server5List(){system.out.println (" server is accessed... ); Return Arrays. AsList (new User (2, "li si 1", "shenzhen"), the new User (3, "li si 2", "shenzhen"), the new User (4, "li si 3", "shenzhen")); }Copy the code

Client call

/ * * * return type for the List with generic * / @ Test public void testServer6 () {String url = "http://localhost:8080/server5"; RestTemplate restTemplate = new RestTemplate(); / / note that the back has a pair of {} ParameterizedTypeReference itself is an abstract class ParameterizedTypeReference < List < User > > = new pr ParameterizedTypeReference<List<User>>() {}; ResponseEntity<List<User>> exchange = restTemplate.exchange(url, HttpMethod.GET, null, pr); System.out.println(exchange.getBody()); }Copy the code

Ok, so that’s the basic use of the RestTemplate