在 Spring 中使用 RestTemplate.例外 - 没有足够的变量可用于扩展 [英] Using RestTemplate in Spring. Exception- Not enough variables available to expand
问题描述
我正在尝试访问 API 的内容,我需要使用 RestTemplate 发送一个 URL.
I am trying to access the contents of an API and I need to send a URL using RestTemplate.
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={"price":"desc"}";
OutputPage page = restTemplate.getForObject(url1, OutputPage .class);
但是,我收到以下错误.
But, I am getting the following error.
Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to expand '"price"'
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:284)
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:220)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:317)
at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:46)
at org.springframework.web.util.UriComponents.expand(UriComponents.java:162)
at org.springframework.web.util.UriTemplate.expand(UriTemplate.java:119)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:501)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239)
at hello.Application.main(Application.java:26)
如果我删除排序标准,它就可以正常工作.我需要使用排序条件解析 JSON.任何帮助将不胜感激.
If I remove the sort criteria, it is working properly. I need to parse the JSON using sort criteria. Any help will be much appreciated.
谢谢
推荐答案
根本原因是 RestTemplate
认为给定 URL 中的花括号 {...}
为URI 变量的占位符,并尝试根据名称替换它们.例如
The root cause is that RestTemplate
considers curly braces {...}
in the given URL as a placeholder for URI variables and tries to replace them based on their name. For example
{pageSize}
会尝试获取一个名为 pageSize
的 URI 变量.这些 URI 变量是用其他一些重载的 getForObject
方法.您尚未提供任何内容,但您的 URL 需要一个,因此该方法会引发异常.
would try to get a URI variable called pageSize
. These URI variables are specified with some of the other overloaded getForObject
methods. You haven't provided any, but your URL expects one, so the method throws an exception.
一种解决方案是创建一个包含值的 String
对象
One solution is to make a String
object containing the value
String sort = "{"price":"desc"}";
并在您的 URL 中提供一个真实的 URI 变量
and provide a real URI variable in your URL
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={sort}";
你会像这样调用你的 getForObject()
OutputPage page = restTemplate.getForObject(url1, OutputPage.class, sort);
我强烈建议您不要在 GET 请求的请求参数中发送任何 JSON,而是在 POST 请求的正文中发送它.
I strongly suggest you do not send any JSON in a request parameter of a GET request but rather send it in the body of a POST request.
这篇关于在 Spring 中使用 RestTemplate.例外 - 没有足够的变量可用于扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!