restTemplate getForObject中map传参问题

十年热恋 提交于 2019-12-01 16:48:59

在使用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就不生效了。

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!