一、RestTemplate简介
1.1、概述
RestTemplate是一种便捷的访问RestFul服务的模板类,是Spring提供的用于访问Rest服务的客户端模板工具集,它提供了多种便捷访问远程HTTP服务的方法。
1.2、API
https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
1.3、如何使用
使用restTemplate访问restful接口非常的简单粗暴无脑,直接调用方法即可:
(url, requestMap, ResponseBean.class)这三个参数分别代表REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。例如:
/*** @Author : 一叶浮萍归大海* @Date: 2023/12/29 16:45* @Description:*/
@Slf4j
@RequestMapping("/consumer/payment")
@RestController
public class OrderController {public static final String PAYMENT_URL = "http://localhost:8001";@Autowiredprivate RestTemplate restTemplate;@PostMapping("/create")public R create(@RequestBody CreatePaymentParam param) {return restTemplate.postForObject(PAYMENT_URL + "/payment/create", param, R.class);}@GetMapping("/getPaymentById/{id}")public R getPaymentById(@PathVariable Long id) {return restTemplate.getForObject(PAYMENT_URL + "/payment/getPaymentById/" + id, R.class, id);}}
1.4、getForObject & getForEntity
(一) getForObject:返回对象为响应体中数据转化成的对象,基本上可以理解为JSON
(二)getForEntity:返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
1.5、postForObject & postForEntity
1.6、GET请求方法
<T> T getForObject(String url, Class<T> responseType, Object... uriVariables);
<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables);
<T> T getForObject(URI url, Class<T> responseType);
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables);
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables);
<T> ResponseEntity<T> getForEntity(URI var1, Class<T> responseType);
1.7、POST请求方法
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType);
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType);