I am trying to query a server that looks like this:
@RequestMapping(value = "/query_user", method = RequestMethod.GET)
public String queryUser(@RequestParam(value="userId", defaultValue="-1") String userId)
{
int id = Integer.parseInt(userId);
User user = this.service.getUser(id);
...
return userJson;
}
This method works when I test with PostMan
private synchronized void callServer(int id)
{
final String URI = "http://localhost:8081/query_user";
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap();
map.add("userId", id);
restTemplate.getMessageConverters()
.add(new MappingJackson2HttpMessageConverter());
// Modified to use getForEntity but still this is not working.
ResponseEntity<String> response
= restTemplate.getForEntity(URI, String.class, map);
}
How can I fix this? It is important that I receive the userJson
from the Server side.
After changing to getForEntity()
method I keep getting the defaultValue
of -1
on the server side. There must be something else wrong with my code. I am definitly sending a userId
that is NOT -1
.
I was able to solve it by using a UriComponentsBuilder
.
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(URI)
.queryParam("userId", id);
Essentially it is appending the parameter to the URI which is what I believe PostMan is doing (that is how I thought about it).
Reference: https://www.oodlestechnologies.com/blogs/Learn-To-Make-REST-calls-With-RestTemplate-In-Spring-Boot