41

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.

user1145874
  • 959
  • 3
  • 13
  • 21

2 Answers2

55

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.

  • Thanks, this worked, but according to the documentation, the option with the uriParams-map should work as well. – user1145874 Dec 20 '13 at 14:44
  • 3
    it works but you need to have variable in your url (it's a map of variables) –  Dec 20 '13 at 14:51
  • 3
    A tiny bit larger answer here would be helpful; when I first read your answer it didn't really click. Take time to show actual snippet of code where you represent the URL as a String and then the value in a map and then calling getForObject(string, map). I up-voted this but it should be made more explicit IMO. – Bane Jul 13 '18 at 17:19
  • 3
    You'd think this would be up-front in the Javadocs...but I had to come here, to a 5-year-old answer, to find it out. – AbuNassar Jul 26 '18 at 00:44
44

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 the answer didn't quite make sense to me at first.

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);
Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82
Bane
  • 1,772
  • 3
  • 21
  • 28
  • 3
    Note that `RestTemplate` also has a method signature that takes varargs, so you can also do this: `int foo = 2; restTemplate.getForObject("http://www.sample.com?foo={foo}", Object.class, foo);` – Nils Breunese Aug 04 '21 at 06:24
  • when using restTemplate, this is the correct answer. – SGuru Oct 04 '22 at 07:47