spring

Spring rest template example

Continuing on our Spring Tutorials, we will try to demonstrate the use of RestTemplate class available in Spring Framework.

The RestTemplate class is the central class in Spring Framework for the synchronous calls by the client to access a REST web-service. This class provides the functionality for consuming the REST Services in a easy and graceful manner. When using the said class the user has to only provide the URL, the parameters(if any) and extract the results received. The RestTemplate manages the HTTP connections.

The RestTemplate inherits from the Restoperations interface and as such, it provides support for consumption of REST web-service for all the major HTTP methods namely GET, POST, PUT, DELETE, OPTIONS and HEAD.

 
Let’s write a sample bean that the RestTemplate class will cast the incoming REST response to.

UserBean.java

package com.jcg.example.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class UserBean
{

		private String userId;

		private String id;

		private String body;

		private String title;



		public String getTitle()
		{
				return this.title;
		}

		public void setTitle(String title)
		{
				this.title = title;
		}

		public String getUserId()
		{
				return this.userId;
		}

		public void setUserId(String userid)
		{
				this.userId = userid;
		}

		public String getId()
		{
				return this.id;
		}

		public void setId(String title)
		{
				this.id = title;
		}

		public String getBody()
		{
				return this.body;
		}

		public void setBody(String body)
		{
				this.body = body;
		}

		@Override
    public String toString()
    {
		    return "UserBean [userId=" + this.userId + ", id=" + this.id + ", body=" + this.body + ", title=" + this.title + "]";
    }


}

@JsonIgnoreProperties(ignoreUnknown = true) is used to inform the RestTemplate to ignore the properties in the JSON response that are not present in the class it is trying to map to, UserBean in this case.

We shall be calling a sample REST service that returns the following JSON response :

sample.json

{
  "userId": 1,
  "id": 1,
  "header": This will be ignored
  "title": "this is a sample title",
  "body": "Sample message in the body"

}

As we can see the JSON response received from the has more parameters than our class has. So the RestTemplate will ignore the rest of the properties that are not present in the PoJo we defined above. Please note that as with other the RestTemplate class assumes that we follow the Bean convention of getters and setters for all the properties in the PoJo, otherwise it throws UnknownProperty Exceptions.

Here’ s the code that makes an actual call to the Service and maps the response to the PoJo.

RestTemplateExample.java

package com.jcg.example;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.jcg.example.bean.UserBean;

public class RestTemplateExample
{
	public static void main(String[] args)
	{
		 RestTemplate restTemplate = new RestTemplate();
		 String url = "http://localhost:8080/SpringMVCloginExample/jsp/json.jsp";
		 List<HttpMessageConverter> messageConverters = 
					new ArrayList<HttpMessageConverter>();
		 MappingJacksonHttpMessageConverter map =
					new MappingJacksonHttpMessageConverter();
		 messageConverters.add(map);
		 restTemplate.setMessageConverters(messageConverters);
		 UserBean bean = restTemplate.getForObject(url, UserBean.class);
		 System.out.println("The object received from REST call : "+bean);
	}
}

The Output:

log4j:WARN No appenders could be found for logger (org.springframework.web.client.RestTemplate).
log4j:WARN Please initialize the log4j system properly.
The object received from REST call : UserBean [userId=1, id=1, title=this is a sample title, 
body=Sample message in the body]

The user can see that the header property in the JSON response has been ignored completely and the UserBean has been constructed by the RestTemplate as expected. This frees up the application developer from opening a HTTP URL, managing the connection exceptions, Closing the connection tunnel etc.

The user needs to set proper HTTPMessageConvertors in the RestTemplate for proper conversion of the messages to the Bean. Here we are using the MappingJacksonHttpMessageConverter from the Jackson Library.

In a development environment, the user is encouraged to put this RestTemplate instantiation logic alongwith other beans in the XML file. This will help build a loosely coupled application.

Here’s the sample way a user can achieve this:

beanConfiguration.xml

 <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
			 </list>
        </property>
    </bean>

The Spring Bean Factory now takes care of instantiation of the Class and injection into the application.

In this example, we demonstrated the consumption of REST Services using only HTTP.GET method. The ,RestTemplate however supports all the HTTP methods. Also, the user can pass parameters to the Service using the overloaded versions like
getForObject(String url, Object request, Class responseType, Object... uriVariables)
postForObject(String url, Object request, Class responseType, Object... uriVariables)

The RestTemplate also supports other custom HTTP methods provided the underlying HTTP library supports the operations.

Download the Source Code

Here we studied how we can use Spring Framework’s RestTemplate class to leverage our application and consume the REST service in an effective way.

Download
You can download the source code of this example here: RestTemplateExample.zip

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button