I have to make a REST
call that includes custom headers and query parameters. I set my HttpEntity
with just the headers (no body), and I use the RestTemplate.exchange()
method as follows:
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
Map<String, String> params = new HashMap<String, String>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);
HttpEntity entity = new HttpEntity(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);
This fails at the client end with the dispatcher servlet
being unable to resolve the request to a handler. Having debugged it, it looks like the request parameters are not being sent.
When I do a an exchange with a POST
using a request body and no query parameters it works just fine.
Does anyone have any ideas?
If you pass non-parametrized params for RestTemplate, you'll have one Metrics for everyone single different URL that you pass, considering the parameters. You would like to use parametrized urls:
instead of
The second case is what you get by using UriComponentsBuilder class.
One way to implement the first behavior is the following:
I take different approach, you may agree or not but I want to control from .properties file instead of compiled Java code
Inside application.properties file
endpoint.url = https://yourHost/resource?requestParam1={0}&requestParam2={1}
Java code goes here, you can write if or switch condition to find out if endpoint URL in .properties file has @PathVariable (contains {}) or @RequestParam (yourURL?key=value) etc... then invoke method accordingly... that way its dynamic and not need to code change in future one stop shop...
I'm trying to give more of idea than actual code here ...try to write generic method each for @RequestParam, and @PathVariable etc... then call accordingly when needed
To easily manipulate URLs / path / params / etc., you can use Spring's UriComponentsBuilder class. It's cleaner that manually concatenating strings and it takes care of the URL encoding for you:
OK, so I'm being an idiot and I'm confusing query parameters with url parameters. I was kinda hoping there would be a nicer way to populate my query parameters rather than an ugly concatenated String but there we are. It's simply a case of build the URL with the correct parameters. If you pass it as a String Spring will also take care of the encoding for you.
I was attempting something similar, and the RoboSpice example helped me work it out:
The uriVariables are also expanded in the query string. For example, the following call will expand values for both, account and name:
so the actual request url will be
Look at HierarchicalUriComponents.expandInternal(UriTemplateVariables) for more details. Version of Spring is 3.1.3.