How to use Spring RestTemplate client for consuming Restful WebService

use-spring-resttemplate-client-consuming-restful-webservice-feature-image

In the tutorial, JavaSampleApproach introduces you a central class RestTemplate that Spring provides for simplified handles restful connection and parsing results.

Related post:
Spring WebClient with Spring Webflux | SpringBoot 2

I. Technology for Spring RestTemplate tutorial

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE

II. Overview

In the tutorial, we create 2 projects, once for restful services, another for rest-template client

1. Project Structure

spring resttemplate project structure

2. Step to do

– Create a Spring Boot project for Restful WebServices & Spring RestTemplate Client
– Create a business model class
– For Restful Web Services, create Controllers: POST, GET, PUT, DELETE
– For Rest-Template client, create Spring Rest-Template with functions: POST, GET, PUT, DELETE
– Apply Rest-Template client
– Build & Enjoys with results

III. Practices
1. Create a Spring Boot project for Restful WebServices

Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, then input needed project info. Press Next, then press Finish, a Spring Boot project will be created successfully.

Open pom.xml file, add Web dependencies:


    org.springframework.boot
    spring-boot-starter-web

2. Create a business model class
package com.javasampleapproach.restfulservice.model;

public class Customer {
	private long id;
	private String name;
	private int age;
	
	public Customer(){
		
	}
	
	public Customer(long id, String name, int  age){
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		String info = String.format("Customer Info: id = %d, name = %s, age = %d", id, name, age);
		return info;
	}

}

3. For Restful Web Services, create Controllers: POST, GET, PUT, DELETE

– Create a RestService class:

@RestController
public class WebController {
    ...
}

– Create a POST request mapping

@RequestMapping(value = "/post", method = RequestMethod.POST)
public String post(@RequestBody Customer cust) {
    System.out.println("/POST request, cust: " + cust.toString());
    return "/Post Successful!";
}

– Create a GET request mapping

@RequestMapping(value = "/get", method = RequestMethod.GET)
public Customer get(@RequestParam("id") long id, @RequestParam("name") String name, @RequestParam("age") int age) {
    String info = String.format("/GET info: id=%d, name=%s, age=%d", id, name, age);
    System.out.println(info);
    return new Customer(id, name, age);
}

– Create a PUT request mapping

@RequestMapping(value= "/put/{id}", method = RequestMethod.PUT)
public void put(@PathVariable(value = "id") long id, @RequestBody Customer cust) {
    String info = String.format("id = %d, custinfo = %s", id, cust.toString());
    System.out.println("/PUT info " + info);
}

– Create a DELETE request mapping

@RequestMapping(value= "/delete/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable(value = "id") long id) {
    String info = String.format("/Delele info: id = %s", id);
    System.out.println(info);
}
4. For Rest-Template client, create Spring Rest-Template with functions: POST, GET, PUT, DELETE

– Create a RestfulService class:

public class RestfulClient {
    RestTemplate restTemplate;
    public RestfulClient(){
    restTemplate = new RestTemplate();
    }
    // ...
}

– With POST request mapping of restful-service, create a POST function:

public void postEntity(){
    System.out.println("Begin /POST request!");
        // replace http://localhost:8080 by your restful services
    String postUrl = "http://localhost:8080/post";
    Customer customer = new Customer(123, "Jack", 23);
    ResponseEntity postResponse = restTemplate.postForEntity(postUrl, customer, String.class);
    System.out.println("Response for Post Request: " + postResponse.getBody());
}

– With GET request mapping of restful-service, create a GET function at rest-template client:

public void getEntity(){
    System.out.println("Begin /GET request!");
    String getUrl = "http://localhost:8080/get?id=1&name='Mary'&age=20";
    ResponseEntity getResponse = restTemplate.getForEntity(getUrl, Customer.class);
    if(getResponse.getBody() != null){
        System.out.println("Response for Get Request: " + getResponse.getBody().toString());    
    }else{
        System.out.println("Response for Get Request: NULL");
    }
}

– With PUT request mapping of restful service, create a PUT function at rest-template client

public void putEntity(){
    System.out.println("Begin /PUT request!");
    String putUrl = "http://localhost:8080/put/2";
    Customer puttCustomer = new Customer("Bush", 23);
    restTemplate.put(putUrl, puttCustomer);
}

– With DELETE request mapping of resful service, create a DELETE function at rest-template client:

public void deleteEntity(){
    System.out.println("Begin /DELETE request!");
    String deleteUl = "http://localhost:8080/delete/1";
    restTemplate.delete(deleteUl);
}

Note: replace localhost:8080 by your restful-services’s host & port

5. Apply Rest-Template client

Use Rest-Template Client has built for communicating with Restful-Services

@SpringBootApplication
@EnableAutoConfiguration(exclude = {EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class})
public class SpringbootResttemplateApplication {
    public static void main(String[] args) {
        RestfulClient restfulClient = new RestfulClient();
        /*
         *POST ENTITY 
         */
        restfulClient.postEntity();
         
        /*
         * GET ENTITY
         */
        restfulClient.getEntity();
         
        /*
         * PUT ENTITY
         */
        restfulClient.putEntity();
         
        /*
         * DELETE ENTITY 
         */
        restfulClient.deleteEntity();
    }
}
6. Build & Enjoys with results

– Build 2 projects: Spring Restful Service and Spring RestTemplate Client.
– Order Run:
1. Run Spring Restful Service
2. Run Spring RestTemplate Client

Result:
1. Logs from Spring Restful Service:

/POST request, cust: Customer Info: id = 123, name = Jack, age = 23
/GET info: id=1, name='Mary', age=20
/PUT info id = 2, custinfo = Customer Info: id = 0, name = Bush, age = 23
/Delele info: id = 1

2. Logs from Spring RestTemplate Client:

Begin /POST request!
Created POST request for "http://localhost:8080/post"
Setting request Accept header to [text/plain, application/json, application/*+json, */*]
Writing [Customer Info: id = 123, name = Jack, age = 23] using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@5579bb86]
POST request for "http://localhost:8080/post" resulted in 200 (OK)
Reading [java.lang.String] as "text/plain;charset=UTF-8" using [org.springframework.http.converter.StringHttpMessageConverter@4bb4de6a]
Response for Post Request: /Post Successful!

Begin /GET request!
Created GET request for "http://localhost:8080/get?id=1&name='Mary'&age=20"
Setting request Accept header to [application/json, application/*+json]
GET request for "http://localhost:8080/get?id=1&name='Mary'&age=20" resulted in 200 (OK)
Reading [class com.javasampleapproach.resttemplate.model.Customer] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@5579bb86]
Response for Get Request: Customer Info: id = 1, name = 'Mary', age = 20

Begin /PUT request!
Created PUT request for "http://localhost:8080/put/2"
Writing [Customer Info: id = 0, name = Bush, age = 23] using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@5579bb86]
PUT request for "http://localhost:8080/put/2" resulted in 200 (OK)

Begin /DELETE request!
Created DELETE request for "http://localhost:8080/delete/1"
DELETE request for "http://localhost:8080/delete/1" resulted in 200 (OK)
IV. Sourcecode

springboot-restful-service
springboot-resttemplate



By grokonez | January 4, 2017.

Last updated on September 6, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*