RestTemplate的异常 Not enough variables available to expand

三世轮回 提交于 2020-01-29 22:06:54

当使用 RestTemplate 可能会遇到异常:

Not enough variables available to expand

典型如下:

@Autowired
private RestTemplate restTemplate;

String url = "http://localhost:8080/search?people={\"name\":\"jack\",\"age\":18}";

String email = restTemplate.getForObject(url, String.class);

这样使用,会出现如下报错信息:

Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to expand '"name"'

这个地方很令人费解,难道不能这样使用?经过一顿查找,发现原来是因为。。。

url因为本身的原因,把花括号 { } 中的内容当成了占位符,而这里又没有明确说明占位符对应的值,所以会导致报错。

只需要简单几步即可解决。在url中使用占位符,将占位符的值即所传 json 放在第3个参数位置。
如下:

String json = {"\"name\":\"jack\",\"age\":18"};
String url = "http://localhost:8080/search?people={json}";
String email = restTemplate.getForObject(url, String.class, json);

这样处理之后,就可以正常使用了。

参考:

原文:https://blog.csdn.net/ezreal_king/article/details/72654440

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