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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM