# RestTemplate **Repository Path**: godchin/RestTemplate ## Basic Information - **Project Name**: RestTemplate - **Description**: RestTemplate基本使用 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-07-20 - **Last Updated**: 2021-12-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 什么是RestTemplate ? `RestTemplate`是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。 ## 如何使用 编写配置类,注入到Spring容器 ``` package com.itdfq.resttemplate.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * @Author GocChin * @Date 2021/7/20 10:51 * @Blog: itdfq.com * @QQ: 909256107 * @Description: */ @Configuration public class ResttemplateConfig { @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } } ``` ## RestTemplate常用请求方法 #### 用于GET请求 - getForObject ![参数](https://img-blog.csdnimg.cn/20210720134927540.png) 源码: ``` @Nullable T getForObject(String var1, Class var2, Object... var3) throws RestClientException; @Nullable T getForObject(String var1, Class var2, Map var3) throws RestClientException; @Nullable T getForObject(URI var1, Class var2) throws RestClientException; ``` - getForEntity ![getForEntity](https://img-blog.csdnimg.cn/20210720135121972.png) 源码: ``` ResponseEntity getForEntity(String var1, Class var2, Object... var3) throws RestClientException; ResponseEntity getForEntity(String var1, Class var2, Map var3) throws RestClientException; ResponseEntity getForEntity(URI var1, Class var2) throws RestClientException; ``` #### 用于POST请求 - postForObject ![postForObject](https://img-blog.csdnimg.cn/20210720135847645.png) 源码: ``` @Nullable T postForObject(String var1, @Nullable Object var2, Class var3, Object... var4) throws RestClientException; @Nullable T postForObject(String var1, @Nullable Object var2, Class var3, Map var4) throws RestClientException; @Nullable T postForObject(URI var1, @Nullable Object var2, Class var3) throws RestClientException; ``` - postForEntity ![postForEntity](https://img-blog.csdnimg.cn/20210720140030700.png) 源码: ``` ResponseEntity postForEntity(String var1, @Nullable Object var2, Class var3, Object... var4) throws RestClientException; ResponseEntity postForEntity(String var1, @Nullable Object var2, Class var3, Map var4) throws RestClientException; ResponseEntity postForEntity(URI var1, @Nullable Object var2, Class var3) throws RestClientException; ``` #### 兼容多种请求方式的exchange - 支持的请求类型有: ``` GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; ``` ![exchange](https://img-blog.csdnimg.cn/20210720140848451.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE3Mjc2,size_16,color_FFFFFF,t_70) ## 例子 ##### 创建实体类 ``` package com.itdfq.resttemplate.entity; import lombok.AllArgsConstructor; import lombok.Data; import java.io.Serializable; /** * @Author GocChin * @Date 2021/7/20 10:54 * @Blog: itdfq.com * @QQ: 909256107 * @Description: */ public class HouseInfo implements Serializable { private static final long serialVersionUID = 7499502427245128735L; private Long l; private String city; private String street; private String address; public HouseInfo() { } public HouseInfo(Long l, String city, String street, String address) { this.l = l; this.city = city; this.street = street; this.address = address; } public static long getSerialVersionUID() { return serialVersionUID; } public Long getL() { return l; } public void setL(Long l) { this.l = l; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "HouseInfo{" + "l=" + l + ", city='" + city + '\'' + ", street='" + street + '\'' + ", address='" + address + '\'' + '}'; } } ``` ##### 编写请求接口 ``` package com.itdfq.resttemplate.controller; import com.itdfq.resttemplate.entity.HouseInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @Author GocChin * @Date 2021/7/20 10:52 * @Blog: itdfq.com * @QQ: 909256107 * @Description: 测试Controller */ @RestController @Slf4j public class HouseController { @GetMapping("/house/data") public HouseInfo getData(@RequestParam("name") String name) { return new HouseInfo(1L, "上海", "虹口", "东体小区"); } @GetMapping("/house/data/{name}") public String getData2(@PathVariable("name") String name) { return name; } @RequestMapping(value = "/house/save", method = RequestMethod.POST) public HouseInfo getData3(@RequestBody HouseInfo houseInfo) { log.info("执行了post请求方法"); return houseInfo; } @RequestMapping(value = "/house/save", method = RequestMethod.POST, headers = {"token=123456"}) public HouseInfo getData4(@RequestBody HouseInfo houseInfo) { log.info("执行了post 带heads的方法"); houseInfo.setCity("海南"); return houseInfo; } } ``` ##### 测试 - Get请求测试 ``` /** * 发送Get请求,传递参数 * @param name * @return */ @GetMapping("/test1/data") public String test1(@RequestParam("name") String name) { //使用getForObject String forObject = restTemplate.getForObject("http://localhost:8081/house/data?name="+name, String.class); System.out.println(forObject); //getForEntity ResponseEntity forEntity = restTemplate.getForEntity("http://localhost:8081/house/data?name=123", HouseInfo.class); System.out.println(forEntity); System.out.println(forEntity.getStatusCodeValue()); return forObject; } ``` 结果 ![浏览器](https://img-blog.csdnimg.cn/20210720141410223.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE3Mjc2,size_16,color_FFFFFF,t_70) 控制台: ![控制台](https://img-blog.csdnimg.cn/20210720141447980.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE3Mjc2,size_16,color_FFFFFF,t_70) `注意`: **当请求返回值用实体类接受的话,实体类中需要加上toString方法,否则请求的数据无法转入json** **get请求无法加入请求头,可以自定义拦截器加入请求头,或者使用exchange方法,加入请求头** - Post请求 - 不带请求头 ``` /** * 发送post请求 不带请求头的方法 * */ @GetMapping("/test3/save") public void test3(){ HouseInfo houseInfo2 = new HouseInfo(2l, "杭州", "余杭", "桃花港"); HouseInfo houseInfo1 = restTemplate.postForObject("http://localhost:8081/house/save",houseInfo2 , HouseInfo.class); System.out.println(houseInfo1); } ``` 结果 ![结果](https://img-blog.csdnimg.cn/20210720142149882.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE3Mjc2,size_16,color_FFFFFF,t_70) - 带请求头的post请求 ``` /** * 带请求头的 post方法 * restTemplate.postForEntity():返回的信息比较全面 包含请求body headers 状态等等 */ @GetMapping("/test4/save") public void test4(){ HouseInfo houseInfo2 = new HouseInfo(2l, "杭州", "余杭", "桃花港"); //设置header信息 HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); requestHeaders.add("token","123456"); //封装信息 HttpEntity requestEntity =new HttpEntity(houseInfo2,requestHeaders); HouseInfo houseInfo1 = restTemplate.postForObject("http://localhost:8081/house/save",requestEntity , HouseInfo.class); System.out.println(houseInfo1); } ``` 结果: ![执行结果](https://img-blog.csdnimg.cn/20210720144934686.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE3Mjc2,size_16,color_FFFFFF,t_70) - exchange请求 ``` /** * exchange 可以请求 * GET, * HEAD, * POST, * PUT, * PATCH, * DELETE, * OPTIONS, * TRACE; * 使用exchange 需要制定请求的方式,以及请求参数 */ @GetMapping("/test5/save") public void test5(){ HouseInfo houseInfo2 = new HouseInfo(2l, "杭州", "余杭", "桃花港"); //设置header信息 HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_JSON); requestHeaders.add("token","123456"); //封装信息 HttpEntity requestEntity =new HttpEntity(houseInfo2,requestHeaders); ResponseEntity exchange = restTemplate.exchange("http://localhost:8081/house/save", HttpMethod.POST, requestEntity, HouseInfo.class); System.out.println(exchange.getBody()); } ``` 结果: ![结果](https://img-blog.csdnimg.cn/20210720145123508.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE3Mjc2,size_16,color_FFFFFF,t_70)