RestTemplate的异常 Not enough variables available to expand

当使用 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

posted @ 2020-01-29 20:56  未月廿三  阅读(8230)  评论(2编辑  收藏  举报