SpringCloud- HTTP request tool - RestTemplate

1, Introduction

The mainstream communication protocols for microservices include RPC,Http, and SpringCloud, which are based on the Http Restful style. There are many ways to initiate an Http request in Java, such as Apache's HttpClient, OKHttp, and so on. Spring encapsulates a Restful based and very simple Http client tool RestTemplate. We use it to implement the communication between order service and user service. It should be noted that RestTemplate itself does not have the functions of service discovery and load balancer. The case in this chapter only demonstrates how to use RestTemplate to initiate calls to user services based on ip and port in order services, that is, do not go to the registry and do not use service discovery.

2, Spring cloud uses RestTemplate

1, Register BEAN

    // If you configure a bean, you can't configure dependency injection later, just as you used to configure dependency injection during ssm integration,
    // Dependency injection is not allowed in code until the configuration file is configured
    // The current file is the spring configuration file
    @Bean
    @LoadBalanced //Let this RestTemplate have the ability of client load balancing when requesting
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

2, GET request

RestTemplate can send HTTP GET requests. Two methods are often used:

  1. getForObject()
  2. getForEntity()

The main difference between the two is that the return value of getForObject() is the response body of HTTP protocol. getForEntity() returns ResponseEntity, which is the encapsulation of HTTP response. In addition to the response body, it also contains HTTP status code, contentType, contentLength, Header and other information.

1. getForObject() accepts the result data in the form of String

    @GetMapping("/payment/get/{id}")
    public String getPayment_String(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, String.class);
    }

2. getForObject() accepts the result data as an object

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

3. getForObject() receives the request result in an array

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment>[] getPayment_array(@PathVariable("id") Long id) {
        CommonResult[] commonResults = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult[].class);
        return commonResults;
    }

4. getForEntity() method

Getforebject request parameter passing method and getForEntity can be used, and the use methods are almost the same, except for a slight difference when the returned results are received. Use ResponseEntity responseEntity to receive response results. Use responseentity Getbody() gets the response body. The response content is consistent with the result returned by the getForObject method. The rest of the response information is the more content of getForEntity than getforebject.

HttpStatus statusCode = responseEntity.getStatusCode(); Get the overall response status information
int statusCodeValue = responseEntity.getStatusCodeValue(); Get response code value
HttpHeaders headers = responseEntity.getHeaders(); Get response header
    @GetMapping("/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        entity.getStatusCode();//Get the overall response status information
        entity.getStatusCodeValue();//Get response code value
        entity.getHeaders();//Get response header
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();

        } else {
            return new CommonResult<>(444, "operation failed");
        }
    }

3, POST request

The POST request method is similar to the GET request method. The POST request of RestTemplate also contains two main methods:

  1. postForObject()
  2. postForEntity()

The main difference between the two is that the return value of postForObject() is the response body of HTTP protocol. postForEntity() returns ResponseEntity, which is the encapsulation of HTTP response. In addition to the response body, it also contains HTTP status code, contentType, contentLength, Header and other information.

1. Send JSON format request to postForObject

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {

        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

2. postForObject simulates form data submission

public void testForm() {
   // Request address
   String url = "http://jsonplaceholder.typicode.com/posts";

   // Request header setting, data in x-www-form-urlencoded format
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

   //Submit parameter settings
   MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
   map.add("title", "zimug Publish the second article");
   map.add("body", "zimug Release the second test content of the article");

   // Assembly request body
   HttpEntity<MultiValueMap<String, String>> request =
               new HttpEntity<MultiValueMap<String, String>>(map, headers);

   // Send the post request, print the result, and receive the response result JSON String as String type
   String result = restTemplate.postForObject(url, request, String.class);
   System.out.println(result);
}

3. postForEntity() method

The postforebject request parameter transfer method and postForEntity can be used, and the use methods are almost the same, except for a slight difference when the return result is received. Use ResponseEntity responseEntity to receive response results. Use responseentity Getbody() gets the response body. The response volume is consistent with the result returned by the postForObject method. The rest of the response information is the more content of postForEntity than postforebject.

HttpStatus statusCode = responseEntity.getStatusCode();Get the overall response status information
int statusCodeValue = responseEntity.getStatusCodeValue(); Get response code value
HttpHeaders headers = responseEntity.getHeaders();Get response header
@Test
public void testEntityPoJo() {
   // Request address
   String url = "http://jsonplaceholder.typicode.com/posts";

   // Data object to send
   PostDTO postDTO = new PostDTO();
   postDTO.setUserId(110);
   postDTO.setTitle("zimug Publish articles");
   postDTO.setBody("zimug Post test content");

   // Send a post request and output the result
   ResponseEntity<String> responseEntity
               = restTemplate.postForEntity(url, postDTO, String.class);
   String body = responseEntity.getBody(); // Get response body
   System.out.println("HTTP response body: " + postDTO.toString());


   //The following is more about postForEntity than postforebject
   HttpStatus statusCode = responseEntity.getStatusCode(); // Get response code
   int statusCodeValue = responseEntity.getStatusCodeValue(); // Get response code value
   HttpHeaders headers = responseEntity.getHeaders(); // Get response header


   System.out.println("HTTP Response status:" + statusCode);
   System.out.println("HTTP Response status code:" + statusCodeValue);
   System.out.println("HTTP Headers Information:" + headers);
}

4. Use of the postForLocation() method

The type, number and usage of parameters passed by postForLocation are basically the same as those of postforebject() or postForEntity(). The only difference from the first two is that the return value is a URI. The returned value of the URI reflects the page Jump after data submission, or the next data operation URI after data submission.

@Test
public void testURI() {
   // Request address
   String url = "http://jsonplaceholder.typicode.com/posts";

   PostDTO postDTO = new PostDTO();
   postDTO.setUserId(110);
   postDTO.setTitle("zimug Publish articles");
   postDTO.setBody("zimug Post test content");

   // Send a post request and output the result
   URI uri = restTemplate.postForLocation(url,postDTO);
   System.out.println(uri);
}

Keywords: leetcode

Added by Viruthagiri on Mon, 03 Jan 2022 08:48:28 +0200