在Spring中使用RestTemplate异常-没有足够的变量可用于展开 报错 拼音 双语对照

问题描述

根本原因是将给定URL中的RestTemplate花括号{...}视为URI变量的占位符,并尝试根据其名称替换它们。例如

{pageSize}

会尝试获取名为的URI变量pageSize。这些URI变量是通过其他一些重载getForObject方法指定的。你没有提供任何内容,但你的URL需要一个,因此该方法将引发异常。

一种解决方案是使String包含该值的对象

String sort = "{\"price\":\"desc\"}";

并在你的网址中提供真实的URI变量

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请求的正文中发送。

解决方法

我正在尝试访问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。任何帮助都感激不尽。

谢谢

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...