Spring Boot receives requests from other services - RestTemplate is simple to use

When using RestTemplate, you can send HTTP requests and process responses. Here is an example of common usage using RestTemplate:

Send a GET request and handle the response:

RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
String responseBody = response.getBody();
// 对响应进行处理

In the above example, we created a RestTemplate instance and used getForEntity()method to send GET request and parse the response as String type. You can change the URL and response type as needed.

Send a POST request and handle the response:

RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requestBody = "{\"key\": \"value\"}";
// requestBody 参数也可以是任意类型(泛型)
// public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers)

HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
String responseBody = response.getBody();
// 对响应进行处理
// 比如转成map
Map<String, Object> map = JSONObject.parseObject(responseBody.getBody());

In this example, we use postForEntity()the method to send a POST request and pass JSON data in the request body. You can set request headers, request body and response type according to your needs.

Send a PUT request:

RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requestBody = "{\"key\": \"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
restTemplate.put(url, requestEntity);

In this example, we use put()the method to send a PUT request and pass JSON data in the request body. You can set request headers and request body as needed.

Send DELETE request:

RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource/{id}";
restTemplate.delete(url, 1);

In this example, we use delete()the method to send the DELETE request, and set the parameters in the URL through placeholders. You can set placeholder parameters as needed.

This is just the basic usage of RestTemplate, you can also use other methods, such as exchange(), execute(), etc., to meet different needs. In addition, there is a more modern way to use WebClient to send HTTP requests, which is a non-blocking, responsive HTTP client introduced in Spring 5.

Guess you like

Origin blog.csdn.net/Aoutlaw/article/details/131584752