The commonly used methods for calling microservices to each other are

HttpUrlConnection or classic network access framework HttpClient

However, in the Spring project, using RestTemplate is clearly more convenient

RestTemplate

Introduction:

RestTemplate is an HTTP request tool supported since Spring 3.0, which provides templates for common REST request schemes, such as GET requests, POST requests, PUT requests, DELETE requests, and some common request execution methods such as exchange and execute. The RestTemplate inherits from InterceptingHttpAccessor and implements the RestOperations interface, which defines basic RESTful operations that are implemented in the RestTemplate.

usage

GET request

1.getForEntity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
public class UseHelloController {
@Autowired
RestTemplate restTemplate;
@GetMapping("/hello")
public String hello(String name) {
.....
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, name);
StringBuffer sb = new StringBuffer();
HttpStatus statusCode = responseEntity.getStatusCode();
String body = responseEntity.getBody();
....
}
}

The first parameter is the URL, which has a placeholder {1}. If there are multiple placeholders represented by {2}, {3}…, the second parameter is the data type returned by the interface, and finally, a variable length parameter is used to fill in values for the placeholder.

Two other parameter formats

  • Placeholders do not use numbers, but instead use the key of the parameter, while placing the parameter in a map. The key in the map corresponds to the key in the placeholder, and the value in the map is the specific value of the parameter. For example, in the above request, the map is used to pass the parameter, and the request method is as follows:
    1
    2
    3
    4
    Map<String, Object> map = new HashMap<>();
    String url = "http://" + host + ":" + port + "/hello?name={name}";
    map.put("name", name);
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map);
  • The second option is to use Uri objects. When using Uri objects, parameters can be directly concatenated into addresses, such as the following:
    1
    2
    3
    String url = "http://" + host + ":" + port + "/hello?name="+ URLEncoder.encode(name,"UTF-8");
    URI uri = URI.create(url);
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
    2.getForObject

The method usage is similar to the above, with the only difference being that the return value of getForObject is the data returned by the service provider, and using getForObject cannot obtain the response header.

POST request

1.postForEntity

1
2
3
4
5
String url = "http://" + host + ":" + port + "/hello2";
MultiValueMap map = new LinkedMultiValueMap();
map.add("name", name);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);
return responseEntity.getBody();

The first parameter of the postForEntity method is the request address, the second parameter is the map object, which stores the request parameter key/value, and the third parameter is the returned data type

1
2
3
4
5
User u1 = new User();
u1.setUsername("Tom");
u1.setAddress("China");
ResponseEntity<User> responseEntity = restTemplate.postForEntity(url, u1, User.class);
return responseEntity.getBody();

2.postForObject

PostForObject and postForEntity are basically the same, except for different return types, which will not be repeated here.

3.postForLocation

1
String s = restTemplate.getForObject(uri, String.class);

PUT request

provider

1
2
3
4
5
6
7
8
9
10
@PutMapping("/user/name")
@ResponseBody
public void updateUserByUsername(User User) {
System.out.println(User);
}
@PutMapping("/user/address")
@ResponseBody
public void updateUserByAddress(@RequestBody User User) {
System.out.println(User);
}

Caller

1
2
3
4
5
6
7
8
MultiValueMap map = new LinkedMultiValueMap();
map.add("username", "Tom");
map.add("address", "China");
restTemplate.put(url1, map);
User u1 = new User();
u1.setAddress("American");
u1.setUsername("Jack");
restTemplate.put(url2, u1);

DELETE request

provider

1
2
3
4
5
6
7
8
9
10
@DeleteMapping("/user/{id}")
@ResponseBody
public void deleteUserById(@PathVariable Integer id) {
System.out.println(id);
}
@DeleteMapping("/user/")
@ResponseBody
public void deleteUserByUsername(String username) {
System.out.println(username);
}

Caller

1
2
3
4
5
6
7
8
9
10
11
12
13
@GetMapping("/hello10")
public void hello10() {
List<ServiceInstance> list = discoveryClient.getInstances("provider");
ServiceInstance instance = list.get(0);
String host = instance.getHost();
int port = instance.getPort();
String url1 = "http://" + host + ":" + port + "/user/{1}";
String url2 = "http://" + host + ":" + port + "/user/?username={username}";
Map<String,String> map = new HashMap<>();
map.put("username", "Tom");
restTemplate.delete(url1, 99);
restTemplate.delete(url2, map);
}