我正在尝试使用像这样的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)
答案 0 :(得分:6)
RestTemplate
似乎没有办法忽略{...}
。相反,请从URI
值生成String
(不包含{}
}。
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();
并使用重载的getForObject
方法,该方法需要URI
。
答案 1 :(得分:-1)
你应该看到RestTemplate的秘密。 getForObject的方法需要三个参数,比如
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables)
&#39; url&#39;是网址前缀的一部分(在&#39;?&#39;之前)和&#39; urlVariables&#39;是一组参数。