Spring Restful client - RestTemplate example

We have already seen Spring restful web services crud example. We have used postmon utility to demonstrate all HTTP methods such as get, post, delete and put but if you want to write java code for restful client , you can use Spring RestTemplate.

You can always use java 's HttpClient but Spring RestTemplate provides more methods and options that you can use to consume Spring restful web services via Http methods.

Here is list of methods provided by Spring Resttemplate for each http methods.

Method
Spring RestTemplate's method
Get
 getForObject, getForEntity
Post
postForObject(String url, Object request, Class responseType, String…​ uriVariables)
postForLocation(String url, Object request, String…​ urlVariables), 
Put
put(String url, Object request, String…​urlVariables)
Delete
delete()
Head
headForHeaders(String url, String…​ urlVariables)
Options
optionsForAllow(String url, String…​ urlVariables)
I am using same example which we have seen in Spring rest crud example. I am using java client instead of postman to consure Rest APIs.

Get example:

You can use getForObject or getForEntity for calling http get method.

Spring Rest API Code get method:

 @RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
 public Country getCountryById(@PathVariable int id) {
  return countryService.getCountry(id);
 }

Spring RestTemplate get Method :

package org.arpit.java2blog.client;

import org.arpit.java2blog.bean.Country;
import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

  RestTemplate restTemplate = new RestTemplate();
  Country bhutan = restTemplate
    .getForObject("http://localhost:8080/SpringRestfulWebServicesCRUDExample/country/{id}", Country.class,2);
  System.out.println("Country Name:"+bhutan.getCountryName());
  System.out.println("Population:"+bhutan.getPopulation());  
 }
}
When you run above code, you will get below output:
Country Name:Bhutan
Population:7000

Post example :

You can use PostForObject or PostForLocation to call post method.

Spring Rest API Code post method:

 @RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
 public Country addCountry(@RequestBody Country country) {
  return countryService.addCountry(country);
 }

Spring RestTemplate post Method :

package org.arpit.java2blog.client;

import org.arpit.java2blog.bean.Country;
import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

  RestTemplate restTemplate = new RestTemplate();

     final String uri = "http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries";
  
     Country country = new Country();
     country.setCountryName("USA");
     country.setPopulation(4000);
  
     Country addedCountry = restTemplate.postForObject( uri, country, Country.class);
     System.out.println("Country added : " +addedCountry.getCountryName());   
 }
}
When you run above code, you will get below output:
Country added : USA

Put example :

You can use put to call http put method.

Spring Rest API Code put method:

 
 @RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
 public Country updateCountry(@RequestBody Country country) {
  return countryService.updateCountry(country);
 }

Spring RestTemplate put Method :

package org.arpit.java2blog.client;

import java.util.HashMap;
import java.util.Map;

import org.arpit.java2blog.bean.Country;
import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

      final String uriForPut = "http://localhost:8080/SpringRestfulWebServicesCRUDExample/countries";
        
      Country country = new Country();
      country.setId(2);
      country.setCountryName("Bhutan");
      country.setPopulation(10000);
    
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.put ( uriForPut, country);  
 }
}
When you run above code, population for bhutan will be updated to 10000.

Delete example :

You can use delete to call http delete method.

Spring Rest API Code delete method:

 
  @RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
 public void deleteCountry(@PathVariable("id") int id) {
  countryService.deleteCountry(id);

 } 

Spring RestTemplate delete Method :

package org.arpit.java2blog.client;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.client.RestTemplate;
/**
 * @author Arpit Mandliya
 */
public class SpringRestTemplateExample {

 public static void main(String args[]) {

   final String uriForDelete = "http://localhost:8080/SpringRestfulWebServicesCRUDExample/country/{id}";
      
      Map<String, String> params = new HashMap<String, String>();
      params.put("id","2");
    
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.delete ( uriForDelete,params);  
 }
}
When you run above code, bhutan will be deleted from list of countries.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012