0

I am trying to query a server that looks like this:

Server Code

@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

Client Code

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.


EDIT

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.

J_Strauton
  • 2,270
  • 3
  • 28
  • 70

2 Answers2

1

Your queryUser() method mapped to GET; from client you call POST restTemplate.postForEntity

J_Strauton
  • 2,270
  • 3
  • 28
  • 70
Bor Laze
  • 2,458
  • 12
  • 20
  • Good catch! Could you post the entire answer for anyone who has similar question?. For example I changed the call but the parameter order is now different. Also I am getting the `defaultValue` of `-1` on the server. – J_Strauton Feb 02 '19 at 18:37
  • The `defaultValue` for `userId` is being used. I am sending a different number than `-1`. I think I am doing something else wrong. Please help. – J_Strauton Feb 02 '19 at 18:45
  • I'm not sure, but try `final String URI = "http://localhost:8081/query_user?{userId}";` – Bor Laze Feb 02 '19 at 18:47
  • Thanks for suggestion. It causes another `-1`. – J_Strauton Feb 02 '19 at 18:50
  • Strange... Sorry, no more ideas this time :( Take a look here - may be it will be helpful https://stackoverflow.com/a/25434451/4362486 – Bor Laze Feb 02 '19 at 18:55
  • Thank you! You were a tremendous help and without you I wouldn't have solved this problem. +1 for you :D – J_Strauton Feb 02 '19 at 19:09
0

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

J_Strauton
  • 2,270
  • 3
  • 28
  • 70