Spring RestTemplate GET with parameters
To easily manipulate URLs / path / params / etc., you can use Spring's UriComponentsBuilder class. It's cleaner than manually concatenating strings and it takes care of the URL encoding for you:
HttpHeaders headers = new HttpHeaders();headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("msisdn", msisdn) .queryParam("email", email) .queryParam("clientVersion", clientVersion) .queryParam("clientType", clientType) .queryParam("issuerName", issuerName) .queryParam("applicationName", applicationName);HttpEntity<?> entity = new HttpEntity<>(headers);HttpEntity<String> response = restTemplate.exchange( builder.toUriString(), HttpMethod.GET, entity, String.class);
The uriVariables are also expanded in the query string. For example, the following call will expand values for both, account and name:
restTemplate.exchange("http://my-rest-url.org/rest/account/{account}?name={name}", HttpMethod.GET, httpEntity, clazz, "my-account", "my-name");
so the actual request url will be
http://my-rest-url.org/rest/account/my-account?name=my-name
Look at HierarchicalUriComponents.expandInternal(UriTemplateVariables) for more details.Version of Spring is 3.1.3.
Since at least Spring 3, instead of using UriComponentsBuilder
to build the URL (which is a bit verbose), many of the RestTemplate
methods accept placeholders in the path for parameters (not just exchange
).
From the documentation:
Many of the
RestTemplate
methods accepts a URI template and URI template variables, either as aString
vararg, or asMap<String,String>
.For example with a
String
vararg:
restTemplate.getForObject( "http://example.com/hotels/{hotel}/rooms/{room}", String.class, "42", "21");
Or with a
Map<String, String>
:
Map<String, String> vars = new HashMap<>();vars.put("hotel", "42");vars.put("room", "21");restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{room}", String.class, vars);
If you look at the JavaDoc for RestTemplate
and search for "URI Template", you can see which methods you can use placeholders with.