相关文章推荐
俊秀的松球  ·  Exchange Online ...·  11 月前    · 
强悍的毛豆  ·  authentication - ...·  1 年前    · 
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就不生效了。