Spring RestTemplate 用法总结

来源:互联网 发布:windows重置出现问题 编辑:程序博客网 时间:2024/06/15 04:15
前言 

由于架构改造,以及程序的通用性,现在工程所以基础数据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进行工作了,后续会对原理,以及其他方法做出总结
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果6p16g不够用怎么办 魅蓝手机内存不够用怎么办 3dmax灯光全黑怎么办 高压15o低压1oo怎么办 源码一位乘法中c怎么办 怀孕搬了重东西怎么办 深蹲力量不涨怎么办 ps4连接显示器分辨率低怎么办 大疆失去链接后怎么办 脑袋被锤了几拳怎么办 华为手机变板砖怎么办 电脑网页打开很慢怎么办 网页加载速度太慢.怎么办 cad字显示不出来怎么办 dell笔记本打不开机怎么办 手机系统界面已停止运行怎么办 大石退出菊丸怎么办 word空白页面突然变大了怎么办 高速上车胎爆了怎么办 没有定速巡航跑长途怎么办 惠普笔记本驱动无法安装怎么办 狙击手遇到热追踪导弹怎么办 做完卷腹脖子疼怎么办 医疗设备销售遭遇瓶颈怎么办 给顾客加油加超了怎么办 卡密码输错两次怎么办 擤鼻涕耳朵会响怎么办 鼻子里有血丝是怎么办 怀孕8周上火了怎么办 鼻炎犯了鼻涕流不停怎么办 擤鼻涕眼睛肿了怎么办 感冒咳嗽鼻子不通气怎么办 宝宝感冒不会擤鼻涕怎么办 新生儿鼻腔里有鼻涕怎么办 宝宝鼻腔有鼻涕出不来怎么办 怀孕的人感冒了怎么办 孕37周感冒咳嗽怎么办 吹鼻涕耳朵堵了怎么办 怀孕的孔雀鱼生病了怎么办 生病了咳嗽一直不好怎么办 宝宝生病治疗后咳嗽怎么办