我正在尝试访问 API 的内容,并且需要使用 RestTemplate 发送 URL。
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={\"price\":\"desc\"}";
OutputPage page = restTemplate.getForObject(url1, OutputPage .class);
但是,我收到以下错误。
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。
任何帮助都感激不尽。
Thanks
根本原因在于RestTemplate
考虑大括号{...}
在给定的 URL 中作为 URI 变量的占位符,并尝试根据它们的名称替换它们。例如
{pageSize}
会尝试获取一个名为的 URI 变量pageSize
。这些 URI 变量是用其他一些重载的变量指定的getForObject http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#getForObject-java.lang.String-java.lang.Class-java.util.Map-方法。您尚未提供任何内容,但您的 URL 需要提供一个,因此该方法会引发异常。
一种解决方案是制作一个String
包含值的对象
String sort = "{\"price\":\"desc\"}";
并在 URL 中提供真实的 URI 变量
String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={sort}";
你会打电话给你的getForObject()
like so
OutputPage page = restTemplate.getForObject(url1, OutputPage.class, sort);
我强烈建议您不要在 GET 请求的请求参数中发送任何 JSON,而是在 POST 请求的正文中发送。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)