Software Development

Consume RESTful Web Services in Java using RestTemplate

[wp_ad_camp_1]

This post demonstrates how to use Spring’s RestTemplate to consume RESTful web services in Java. The codes used are used in a SOA or Microservices context but the key code snippet is about RestTemplate.

3 Maven Projects

There are 3 Maven projects used for this post:

  1. common-dto-api
    • This contains all Data Transfer Objects (DTOs) used, in this case, to exchange data between a config server and a client service.
  2. com-turreta-soademo-configserver
    • This represents the config server.
    • For this demo, it is configured to run on port 8080.
  3. com-turreta-soademo-clientservice
    • This represents the client service that consumes (RESTful) services available on the config server
    • For this demo, it is configured to run on port 8081.
    • It has a single @RestController which you can test if the two applications work nicely with each other. See Demo Test section below.

Remote Service to Test RestTemplate

Our config server provides a RESTful web service for our client to consume using RestTemplate.

[wp_ad_camp_2]

Our Client Service

Our client service has one @RestController. The important lines are lines 24-27 which enable us to perform HTTP POST using RestTemplate.

[wp_ad_camp_3]

HTTP GET, PUT, and DELETE

This post demonstrates the use of HTTP POST using RestTemplate.Here are code snippets when using the other 3 important HTTP methods.

[wp_ad_camp_4]

HTTP GET

HTTP PUT

HTTP DELETE

Demo Test

[wp_ad_camp_5]

Download the Codes

The codes are available on GitHub.com and are 3 Maven projects in a single repository. You may need to build them individually first starting with the DTO project. Please see Build/Install Maven Projects in Separate Directors in Travis CI via GitHub

Download from

https://github.com/Turreta/spring-rest-template-demo

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like