问题
I try to access a rest endpoint by using springs RestTemplate.getForObject() but my uri variables are not expanded, and attached as parameters to the url. This is what I got so far:
Map<String, String> uriParams = new HashMap<String, String>();
uriParams.put("method", "login");
uriParams.put("input_type", DATA_TYPE);
uriParams.put("response_type", DATA_TYPE);
uriParams.put("rest_data", rest_data.toString());
String responseString = template.getForObject(endpointUrl, String.class, uriParams);
the value of the endpointUrl Variable is http://127.0.0.1/service/v4_1/rest.php
and it's exactely what it's called but I'd expect http://127.0.0.1/service/v4_1/rest.php?method=login&input_type...
to be called.
Any hints are appreciated.
I'm using Spring 3.1.4.RELEASE
Regards.
回答1:
There is no append some query string logic in RestTemplate it basically replace variable like {foo}
by their value:
http://www.sample.com?foo={foo}
becomes:
http://www.sample.com?foo=2
if foo
is 2.
回答2:
The currently-marked answer from user180100 is technically correct but not very explicit. Here is a more explicit answer, to help those coming along behind me, because when I first read zhe's answer it didn't make sense to me.
String url = "http://www.sample.com?foo={fooValue}";
Map<String, String> uriVariables = new HashMap();
uriVariables.put("fooValue", 2);
// "http://www.sample.com?foo=2"
restTemplate.getForObject(url, Object.class, uriVariables);
回答3:
RC.'s Accepted Answer is correct about the params map needing variable markers in the url String to replace into ("foo" in "//www.sample.com?foo={foo}" gets replaced with the key mapped by "foo" in your params map).
It is technically also possible to explicitly code the params into the URL String itself to begin with like:
endpointUrl = endpointUrl + "?method=login&input_type=" + DATA_TYPE + "&rest_data=" + rest_data.toString();
来源:https://stackoverflow.com/questions/20705377/resttemplate-urivariables-not-expanded