介绍
:::tips
RestTemplate是Spring家族中一款基于Http协议的组件,用来实现基于Http协议的服务之间的通信(也就是服务调用)
RestTemplate采用同步方式执行Http请求的类,底层使用JDK原生HttpURLConnection API,或者HttpComponents等其他HTTP客户端请求类库
简单理解:RestTemplate是Spring提供的一个用来模拟浏览器发送请求和接收响应的类,能够远程调用API :::
使用
注册RestTemplate
:::info 将RestTemplate注册到Spring容器中 :::
@Configurationpublic class WebConfig{//注册RestTemplate@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}}
注入RestTemplate
在需要使用的类中注入RestTemplate,在需要调用接口的地方调用restTemplate的方法(此处调用的方法取决于请求方式:如get、put、post、delete等),指定参数一为请求地址,指定参数二为类名.class,调用restTemplate的方法发起请求后得到的响应数据就会封装到这个类的对象中,将返回值接收一下,就得到了指定类型的对象
//注入RestTemplate@Autowiredprivate RestTemplate restTemplate;
Get请求
:::tips 普通Get请求 :::
@SpringBootTestpublic class MyTest{//注入RestTemplate@Autowiredprivate RestTemplate restTemplate;@Testpublic void test(){//发起Get请求类名 对象名 = restTemplate.getForObject("请求地址",类名.class);}}
:::tips Get请求携带Json数据 :::
@SpringBootTestpublic class MyTest{//注入RestTemplate@Autowiredprivate RestTemplate restTemplate;@Testpublic void test(){Map<String, Object> map = new HashMap<>();map.put("name", "zhangsan");map.put("id", 18);//发起Get请求并携带Json数据类名 对象名 = restTemplate.getForObject("请求地址", 类名.class, map);}}
