Spring - RestTemplate example

[Last Updated: Aug 16, 2017]

The RestTemplate (included in Spring-web module) is the core class for client-side access to RESTful services.

In this quick example, we will learn how to use RestTemplate for making an HTTP GET method request and capture the response.


A simple Spring Restful Service

public class UserController {

  public String getUserById(@PathVariable("id") String userId) {
      return "returning dummy user with id " + userId;

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Service client using RestTemplate

public class UserClient {

  public static void main(String[] args) {
      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> responseEntity = restTemplate.getForEntity(
              "http://localhost:8080/users/40", String.class);
      System.out.println("-- response --");
      System.out.println("status: "+responseEntity.getStatusCodeValue());
      System.out.println("headers: "+responseEntity.getHeaders().toSingleValueMap());
      System.out.println("body: "+responseEntity.getBody());


-- response --
status: 200
headers: {Server=Apache-Coyote/1.1, Content-Type=text/plain;charset=ISO-8859-1, Content-Length=31, Date=Wed, 16 Aug 2017 19:57:20 GMT}
body: returning dummy user with id 40

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Spring RestTemplate GET example Select All Download
  • rest-template-get-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • client
                  • server

    See Also