restTemplate getForObject中map传参问题


在使用restTemplate中getForObject的map传参形式时:

开始时我是这么调用的:

RestTemplate rest = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("s", "hello");
String url = "http://localhost:8990/drce/hello";
String s = rest.getForObject(url , String.class,params);
System.out.println(s);

结果是服务端接收不到参数,报参数异常

 

 问题就出在第一次参数“url”这里了,这里的url需要携带参数,格式为url+?服务端参数名={map参数名}

改写为一下写法就可以正常运行了:

RestTemplate rest = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("s", "hello");
String url = "http://localhost:8990/drce/hello";
String s = rest.getForObject(url + "?s={s}", String.class,params);
System.out.println(s);

 

在看源码后,了解到restTemplate会用一个工具类去解析前面的url,提取出host,port等信息,如果不加参数,他就认为你不需要传参,所以map就不生效了。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM