我正在尝试使用RestTemplate执行URL,如下所示 -
public static void main(String[] args) throws UnsupportedEncodingException {
RestTemplate restTemplate = new RestTemplate();
String url = "http://ptr.vip.host.com/pss/repositories/pssdb/branches/main/query/Service[@alias="
+ "hello"
+ "].serviceInstances.runsOn{@resourceId}?allowScan=true&limit=10000&skip=0";
try {
String response = restTemplate.getForObject(url, String.class);
System.out.println(response);
} catch (RestClientException ex) {
ex.printStackTrace();
}
}
但每次我遇到这样的错误时——
Exception in thread "main" java.lang.IllegalArgumentException: Not enough variable values available to expand '@resourceId'
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:272)
我做错了什么以及如何解决?
更新:-
我也尝试使用此网址,但它对我不起作用。我只是用{{@resourceId}}
替换了{@resourceId}
String url = "http://ptr.vip.host.com/pss/repositories/pssdb/branches/main/query/Service[@alias="
+ "hello"
+ "].serviceInstances.runsOn{{@resourceId}}?allowScan=true&limit=10000&skip=0";
更新-2
这是代码 -
try {
UriComponentsBuilder builder = UriComponentsBuilder
.fromPath("http://ptr.vip.str.host.com/pss/repositories/pssdb/branches/main/query/Service[@alias="
+ "hello"
+ "].serviceInstances.runsOn{@resourceId}?allowScan=true&limit=10000&skip=0");
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
String response = restTemplate.getForObject(uri, String.class);
System.out.println(response);
} catch (RestClientException ex) {
ex.printStackTrace();
}
错误是——
Exception in thread "main" java.lang.IllegalArgumentException: URI is not absolute
at java.net.URI.toURL(URI.java:1095)
at org.springframework.http.client.SimpleClientHttpRequestFactory.createRequest(SimpleClientHttpRequestFactory.java:109)
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:76)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:479)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:460)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:228)
似乎RestTemplate
没有办法忽略{...}
.相反,请从String
值生成URI
(不带双{}
(。
String url = "http://ptr.vip.host.com/pss/repositories/pssdb/branches/main/query/Service[@alias="
+ "hello"
+ "].serviceInstances.runsOn{@resourceId}?allowScan=true&limit=10000&skip=0";
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
并使用需要URI
的重载getForObject
方法。
U 应该看到 RestTemplate 的搜索结果。getForObject 的方法需要三个参数,例如
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables)
"url"是url前缀的一部分(在"?"前面(,"urlVariables"是一个参数数组。