Spring RestTemplate 用法总结

前言  

由于架构改造,以及程序的通用性,现在工程所以基础数据CURD操作,以及基本业务逻辑,均采用Api形式。而调用Api的工程会对数据进行进一步的加工处理、以及错误异常的抛出。 
现在描述一下RestTemplate的几个常用的用法。 

Spring RestTempalte 示例  

配置文件  

按如下方式在springBasic.xml中添加RestTemplat的配置; 
Java代码   收藏代码
  1. <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">  
  2.         <property name="messageConverters">  
  3.             <list>  
  4.                 <bean class="org.springframework.http.converter.FormHttpMessageConverter" />  
  5.                 <bean  
  6.                     class="org.springframework.http.converter.StringHttpMessageConverter" />  
  7.                 <bean  
  8.                     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />  
  9.             </list>  
  10.         </property>  
  11.     </bean>  


为了方便,可以将restTemplat在一个父类中初始化,所有使用restTemplat的类可以继承该父类 

如下 
Java代码   收藏代码
  1. public class BaseController {  
  2.     @Autowired  
  3.     protected  
  4.     RestTemplate restTemplate;  
  5. }  



输入 : 

少量参数 

String 
Integer 
boolean 

多个参数 

Map 
        Map<String,String> 
Map<String,Integer> 
Map<String,Object> 
等等等 

建议  



输出:  
       和Api的返回值有关,一般为ModelMap,而ModelMap为json形式。 

RestTemplate 常用方法手册  

1. 无参数  
    a) /api/common/getlist.json 
2. 少量参数  
    a) 参数在url中;api/muser/getUserInfo/${uid}.json 
    b) 需要传过去参数; 

3. 多个参数  
    a) 手动将参数装入Map中,传过去。注:此时,Api中需要手动获取Map中参数,然后手动组装为对象。不建议此方法 
    b) 将参数为 对象 传给Api 
      i.直接使用Map<String,Objece>传对象; 注:此处需要使用getForObject/postForObject方法,同时在调用处需要手动将Object序列化为json形式 ;其次在向Api传参数时,参数也是以json方式传过去的。我们在接收参数的时候,需要手动将参数反序列化为对应的Object或者List<Object>; 此处需要注意:在反序列化时,有些类型可能不匹配、那么我们需要做一些字符转换器、放在Spring容器中,保证其字段转换。  

4. 常用方法  
      1 restTemplate.getForObject(url, responseType); 
     url:请求的url 
        responseType:返回类型 
      示例:  
      Api代码  
Java代码   收藏代码
  1. /** 
  2.      * 获取数据) 
  3.      * @param modelMap 
  4.      * @return 
  5.      */  
  6.     @RequestMapping(value = "/getlist.json")  
  7.     @ResponseBody  
  8.     public ModelMap getCompanyList(ModelMap modelMap) {  
  9.         modelMap.clear();  
  10.   
  11.         List<ShortCompanyVO> companyList = new ArrayList<ShortCompanyVO>();  
  12.           
  13.         companyList = companyServiceImpl.getAllCompanyList();  
  14.           
  15.         modelMap.put(WebApplicationConstant.FLAG_STATUS, AppConstant.JSON_RESPONSE_STATUS_SUCCESS);  
  16.         modelMap.put(WebApplicationConstant.FLAG_RESULT, companyList);  
  17.           
  18.         log.debug(JsonUtil.map2json(modelMap));  
  19.           
  20.         return modelMap;  
  21. }  


说明:  
b) 根据Api信息可知,此方法不需要任何参数,直接访问即可;返回类型为ModelMap类型,一般为json数据;这时我们可以使用restTemplate.getForObject(url, responseType);方法获取数据,或者使用restTemplate.getForObject(url, responseType);方法获取数据。两种区别在这里不能很好体现,下面仔细讲解。 
c)使用restTemplat代码示例  
Java代码   收藏代码
  1. public class TestTemplate {  
  2.     @Autowired  
  3.     protected RestTemplate restTemplate;  
  4.     @BeforeClass  
  5.     public static void setUpBeforeClass() throws Exception {  
  6.     }  
  7.   
  8.     @Before  
  9.     public void setUp() throws Exception {  
  10.           
  11.     }  
  12.   
  13.     @Test  
  14.     public void test() {  
  15.         String string = restTemplate.getForObject("http://localhost:8080/api/common/getlist.json", String.class);  
  16.   
  17.         System.out.print(string);  
  18.     }  
  19. }  

说明:  
此为不带有任何参数的请求,返回类型根据Api中返回类型来定,String、boolean、int、json等等。 

2.restTemplate.postForObject(url, request, responseType);  
     url:请求的url 
     request:传给Api的数据类型 
     responseType:Api返回的数据类型 

    Api示例  
Java代码   收藏代码
  1. /** 
  2.      * 获取用户信息 
  3.      * @param uid 
  4.      * @return 
  5.      */  
  6.     @RequestMapping(value="/getManageUserInfo/{uid}.json")  
  7.     @ResponseBody  
  8.     public ModelMap getManageUserInfo(ModelMap modelMap, [color=red]@PathVariable(value="uid"long uid[/color], HttpServletRequest request){  
  9.         try {  
  10.             if (uid <= 0) {  
  11.                 modelMap.put("status", AppConstant.STATUS_REQUEST_ERROR);  
  12.                 return modelMap;  
  13.             }  
  14.             AccountUser accountUser = manageAccountService.getManageUserInfo(uid);  
  15.             if (accountUser == null) {  
  16.                 modelMap.put("status", AppConstant.STATUS_SYS_ERROR);  
  17.                 return modelMap;  
  18.             }  
  19.             modelMap.put("status", AppConstant.STATUS_SUCCESS);  
  20.             modelMap.put("result", accountUser);  
  21.         } catch (Exception e) {  
  22.             e.printStackTrace();  
  23.             logger.error("getManageUserInfo is error " + e);  
  24.             modelMap.put("status", AppConstant.STATUS_SYS_ERROR);  
  25.             return modelMap;  
  26.         }  
  27.         return modelMap;  
  28.     }  

说明:  
@PathVariable(value="uid"),因为此参数可以从url中取得,所以我们可以用@PathVariable标签解析url中参数值,(value="uid")代表将名字为uid的值解析出来付给uid这个变量,类型为Long; 
当然我们这时候也可以在方法里面这样写:Long uid = requet.getParameter("uid");这是最传统的方式,适合少量参数; 
也可以直接在方法头这么写public ModelMap getManageUserInfo(ModelMap modelMap,  Long uid , HttpServletRequest request) 
或者这么写public ModelMap getManageUserInfo(ModelMap modelMap,  @RequestParam("uid",required="false")Long uid , HttpServletRequest request);这种写法是用@RequestParam标签代替了上面的Long uid = requet.getParameter("uid");同时,required = false代表,这个参数是非必须的,有没有都可以,不会出现nullPoint异常,这也是这个标签的一个优点。 

但是以上这些都不是最好的,因为当参数很多事,我们一个个传之后继续解析是不是会被累死?或者我们要把Api方法中的方法头写的多么长呢? 

所以我们因为以上方式,我们要 将参数整理为对象传过去 ,这样就可以避免以上问题。 
注意: @ResponseBody这个标签代表要返回数据类型,一定不要忘记。 

Api示例:  
Java代码   收藏代码
  1. package com.bitbao.api.manage.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.ui.ModelMap;  
  7. import org.springframework.web.bind.annotation.PathVariable;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RequestMethod;  
  10. import org.springframework.web.bind.annotation.ResponseBody;  
  11.   
  12. import com.bitbao.api.manage.bean.Student;  
  13.   
  14. /** 
  15.  * Test of RestTemplate 
  16.  * @author qiuying.huang 
  17.  * @since 2013-10-14 
  18.  */  
  19. @RequestMapping("/test")  
  20. @Controller  
  21. public class TestRestTemplate {  
  22.   
  23.     @RequestMapping(value = "/intResult/{param}.json" , method = RequestMethod.GET)  
  24.     @ResponseBody  
  25.     public int intResult(HttpServletRequest request,@PathVariable(value="param"int param){  
  26.         int a = request.getParameter("param") == null ? 0 : Integer.valueOf(request.getParameter("param"));  
  27.         int b = 100;  
  28.         System.out.println("request is " + a );  
  29.         int sum = b+param;  
  30.         return sum;  
  31.     }  
  32.       
  33.     @RequestMapping(value = "/voReturn.json")  
  34.     @ResponseBody  
  35.     public Student voReturn(Student student){  
  36.         return student;  
  37.     }  
  38.       
  39.     @RequestMapping(value = "/mapReturn.json")  
  40.     @ResponseBody  
  41.     public ModelMap mapReturn(ModelMap modelMap){  
  42.         Student student = new Student();  
  43.         student.setName("wang想");  
  44.         modelMap.put("status"0);  
  45.         modelMap.put("student", student);  
  46.         return modelMap;  
  47.     }  
  48. }  


Api调用示例:  

Java代码   收藏代码
  1. import java.util.Map;  
  2.   
  3. import org.junit.Before;  
  4. import org.junit.BeforeClass;  
  5. import org.junit.Test;  
  6. import org.junit.runner.RunWith;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.http.HttpEntity;  
  9. import org.springframework.test.context.ContextConfiguration;  
  10. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  11. import org.springframework.util.LinkedMultiValueMap;  
  12. import org.springframework.util.MultiValueMap;  
  13. import org.springframework.web.client.RestTemplate;  
  14.   
  15. import com.bitbao.manager.bean.Student;  
  16. import com.bitbao.manager.util.JsonUtil;  
  17.   
  18. @RunWith(SpringJUnit4ClassRunner.class)    
  19. @ContextConfiguration(locations={"classpath:spring/root.xml","classpath:spring/dataSource.xml"})    
  20. public class TestTemplate{  
  21.     @Autowired  
  22.     protected RestTemplate restTemplate;  
  23.     @BeforeClass  
  24.     public static void setUpBeforeClass() throws Exception {  
  25.         String url = "";  
  26.     }  
  27.   
  28.     @Before  
  29.     public void setUp() throws Exception {  
  30.           
  31.     }  
  32.   
  33.     @Test  
  34.     /** 
  35.      * 返回Integer、int类型数据 
  36.      */  
  37.     public void testInt() {  
  38.         MultiValueMap<String,Object> dataMap = new LinkedMultiValueMap<String, Object>();  
  39.         int param = 22;  
  40.         dataMap.add("param""23");  
  41.         HttpEntity<Object> entity = new HttpEntity<Object>(dataMap);  
  42.         Integer a = restTemplate.getForObject("http://localhost:8080/test/intResult/" + param + ".json" , Integer.class);//  
  43.         Integer b = restTemplate.getForObject("http://localhost:8080/test/intResult/" + param + ".json" , Integer.class);  
  44.         Integer c = restTemplate.getForObject("http://localhost:8080/test/intResult/" + param + ".json",Integer.class, entity);  
  45.         Integer d = restTemplate.postForObject("http://localhost:8080/test/intResult/" + param + ".json", entity, Integer.class);//此处会报错,因为Api中已经将此访问强制定位为get请求,所以只能使用get请求的方法。  
  46.         System.out.println("testInt a is : " + a);  
  47.         System.out.println("testInt b is : " + b);  
  48.         System.out.println("testInt c is : " + c);  
  49.         System.out.println("testInt d is : " + d);  
  50.     }  
  51.       
  52. //    @Test  
  53. //    public void testString(){  
  54. //      Student student = new Student();  
  55. //      student.setAge(10);  
  56. //      student.setName("sdf");  
  57. //      MultiValueMap<String,String> dataMap = new LinkedMultiValueMap<String, String>();  
  58. //      String stu = JsonUtil.bean2json(student);  
  59. //      dataMap.add("student", stu);  
  60. //        HttpEntity<Object> entity = new HttpEntity<Object>(dataMap);   
  61.         Student student1 = restTemplate.getForObject("http://localhost:8080/test/voReturn.json", Student.class, entity);   
  62. //        Student student1 = restTemplate.postForObject("http://localhost:8080/test/voReturn.json", entity, Student.class);   
  63.         Student student2 = restTemplate.postForObject("http://localhost:8080/test/voReturn.json", stu, Student.class);  
  64. //        System.out.println("testString student1 is :" + student1 );  
  65. //    }  
  66.       
  67.     /** 
  68.      * 返回String、Object数据 
  69.      */  
  70.     @Test  
  71.     public void testString(){  
  72.         Student student = new Student();  
  73.         student.setAge(10);  
  74.         student.setName("sdf");  
  75.         student.setBanji(123);  
  76.         MultiValueMap<String,String> dataMap = new LinkedMultiValueMap<String, String>();  
  77.         String stu = JsonUtil.bean2json(student);  
  78.         System.out.println("stu is " + stu);  
  79.         dataMap.add("student", stu);  
  80.         HttpEntity<Object> entity = new HttpEntity<Object>(dataMap);  
  81.         Student student1 = restTemplate.postForObject("http://localhost:8080/test/voReturn.json" + "?student=" + stu, entity, Student.class);   
  82.         System.out.println("testString student1 is :" + student1 );  
  83.     }  
  84.       
  85.     /** 
  86.      * 返回Map数据 
  87.      */  
  88.     @Test  
  89.     public void testMap(){  
  90.         Map<String, Object> map1 = restTemplate.getForObject("http://localhost:8080/test/mapReturn.json" , Map.class);  
  91.         Map<String, Object> map2 = restTemplate.postForObject("http://localhost:8080/test/mapReturn.json""", Map.class);//此处不需要参数,但是postForObject方法需要参数,所以穿了个"";这段建议使用get方法  
  92.         System.out.println("testMap map1 is :" + map1);  
  93.         System.out.println("testMap map2 is :" + map2);  
  94.     }  
  95.   
  96. }  



说明:  
1.这几个方法说明使用restTemplate的返回类型和Api定义的类型有关; 
2. 注意: @ResponseBody这个标签代表要返回数据类型,一定不要忘记。 
3.假如Api中有声明请求方法为get/post,则,我们只能使用跟其对应的方法; 
例如:testInt() 方法在Api中声明为get、则我们只能使用对应的get请求; 
4.在有很多参数时,我们可以先把参数序列化为json形式,然后使用postForObject;然后将其参数拼装到url中, Student student1 = restTemplate.postForObject("http://localhost:8080/test/voReturn.json" + "?student=" + stu, entity, Student.class);  ;我们在Api中拿到参数后反序列化为对应的Vo; 
注意: 在反序列化过程中,我们会遇到有些字段为null无法转换的情况,所以这时最好写一个null的转换器。尤其类型为int时,无法自动处理此情况,那么可以借助转换器处理。 

遇到问题:今天request.getPetemper("aa"),无法获取数据值,这个原因有待追查。 

总结: 
以上几个方法基本可以使用restTempalate进行工作了,后续会对原理,以及其他方法做出总结
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring RestTemplateSpring框架中的一个重要组件,用于简化HTTP请求的发送。使用RestTemplate可以实现对RESTful Web服务的访问,支持GET、POST、PUT、DELETE等常见的HTTP请求方法。 下面是Spring RestTemplate的一些基本使用方法: 1. 创建RestTemplate实例: ```java RestTemplate restTemplate = new RestTemplate(); ``` 2. 发送GET请求: ```java String url = "http://example.com/users/{userId}"; ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, userId); ``` 3. 发送POST请求: ```java String url = "http://example.com/users"; User user = new User(); ResponseEntity<User> response = restTemplate.postForEntity(url, user, User.class); ``` 4. 发送PUT请求: ```java String url = "http://example.com/users/{userId}"; User user = new User(); restTemplate.put(url, user, userId); ``` 5. 发送DELETE请求: ```java String url = "http://example.com/users/{userId}"; restTemplate.delete(url, userId); ``` RestTemplate还有很多其他的方法,更详细的使用方法可以参考Spring官方文档。 ### 回答2: Spring RestTemplateSpring框架提供的用于处理RESTful请求的模板类。它封装了底层的HTTP通信细节,提供了简化的API,使得开发者可以更方便地发送HTTP请求和接收响应。 在使用RestTemplate之前,我们首先需要在项目的依赖中引入Spring的web模块,因为RestTemplate是web模块的一部分。 使用RestTemplate发送HTTP请求的步骤如下: 1. 创建一个RestTemplate对象。可以直接通过new关键字创建,也可以通过Spring的依赖注入方式获取。 2. 选择合适的请求方法,并设置请求的URL和请求参数。RestTemplate提供了多种请求方法,如GET、POST等。我们可以通过参数的形式传递URL,并可以使用Map或对象封装请求参数。 3. 发送请求,并接收响应。可以调用RestTemplate的exchange()方法来发送请求,并通过ResponseEntity来接收响应。exchange方法可以指定请求方法、URL、请求体、请求头等信息,并可以通过参数化类型来指定响应的类型。 4. 解析响应。根据实际需要,我们可以使用ResponseEntity的getBody()方法获取响应的主体内容,并进行进一步的解析。 需要注意的是,使用RestTemplate发送请求时,我们可以自己编写请求头、请求体等信息,也可以通过使用RestTemplate提供的辅助方法来简化请求的构建。此外,RestTemplate还提供了异常处理和重试机制,可以更好地处理异常情况。 总的来说,Spring RestTemplate提供了简洁易用的API,帮助我们快速发送HTTP请求和处理响应,节省了开发时间和精力。它是Spring框架中非常重要的一部分,值得开发者深入学习和掌握。 ### 回答3: Spring RestTemplateSpring框架中的一个HTTP访问客户端工具,它可以方便地进行HTTP请求的发送和响应的处理。 在使用RestTemplate之前,首先需要引入相关的依赖。在Maven项目中,可以通过在pom.xml文件中添加以下依赖来使用RestTemplate: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 引入依赖后,可以通过如下方式创建一个RestTemplate对象: ``` RestTemplate restTemplate = new RestTemplate(); ``` 之后就可以使用RestTemplate对象来发送HTTP请求了。RestTemplate提供了多种发送请求的方法,例如getForObject()、postForObject()等。 使用getForObject()方法发送GET请求并接收响应: ``` String url = "http://api.example.com/data"; String response = restTemplate.getForObject(url, String.class); ``` 使用postForObject()方法发送POST请求并接收响应: ``` String url = "http://api.example.com/data"; String requestBody = "param1=value1&param2=value2"; String response = restTemplate.postForObject(url, requestBody, String.class); ``` RestTemplate还提供了其他一些方法,例如exchange()方法可以发送更复杂的请求,并接收带有响应头和状态码等信息的响应对象。 在使用RestTemplate发送请求时,可以通过设置请求头、请求体、URI参数等来定制请求。可以通过如下方式来设置请求头: ``` HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer token"); HttpEntity<String> requestEntity = new HttpEntity<>(headers); ``` 可以通过如下方式来设置请求体: ``` MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("param1", "value1"); requestBody.add("param2", "value2"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody); ``` 可以通过如下方式来设置URI参数: ``` String url = "http://api.example.com/data?param1={param1}&param2={param2}"; Map<String, String> uriVariables = new HashMap<>(); uriVariables.put("param1", "value1"); uriVariables.put("param2", "value2"); String response = restTemplate.getForObject(url, String.class, uriVariables); ``` 总结来说,Spring RestTemplate是一个用于发送和处理HTTP请求的方便工具,通过引入相关依赖并创建RestTemplate对象,可以使用它发送不同类型的HTTP请求,并对响应进行处理。通过设置请求头、请求体、URI参数等,可以对请求进行定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值