Query Parameter example

In this post under Spring RestTemplate, I will show with example how to pass query paramter.

For our example I will perform a GET http request on url “http://jsonplaceholder.typicode.com/posts” with “userId” as query parameter.

I will create a url template and then create a map which will contain an entry where key will be “userId” and value be the actual value.

Pass the url template and map as arguments to “getForObject” method of “RestTemplate”

Below is the complete code for your reference

Main Class

package package4;
  
import org.springframework.web.client.RestTemplate;
  
import java.util.HashMap;
  
public class Example4 {
      public static void main(String[] args) {
          RestTemplate restTemplate = new RestTemplate();
          String url = "http://jsonplaceholder.typicode.com/posts?userId={id}";
          HashMap<String, Integer> pathVariables = new HashMap<>(0);
          pathVariables.put("id", 1);
          String post = restTemplate.getForObject(url, String.class, pathVariables);
          System.out.println(post);
     }
}

In the above code, at line 9, I create an instance of “RestTemplate” class.

At line 10, I define a url template. In this template I defined a query parameter named “userId” with placeholder “id” within “{” and “}”.

At line 11, I will create a map which will contain the query parameter name “userId” as key with actual value.

At line 13, I call “getForObject” method and pass three parameters
1) url
2) result type
3) map

The result will be list of posts whose userId is 1. It will be returned as JSON String. In future post I will show how to changed the result type from String to List of Posts class.

At runtime Spring RestTemplate framework using the url template and map come up with the actual url. In this example it will be

http://jsonplaceholder.typicode.com/posts?userId=1

In this way we can pass query paramter.

Leave a comment