Spring Restful client – RestTemplate example

In this tutorial, we will see how to create rest client using Spring RestTemplate.

We have already seen Spring restful web services crud example. We have used postman 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:

Spring RestTemplate get Method :

When you run above code, you will get below output:

Post example :

You can use PostForObject or PostForLocation to call post method.

Spring Rest API Code post method:

Spring RestTemplate post Method :

When you run above code, you will get below output:

Put example :

You can use put to call http put method.

Spring Rest API Code put method:

Spring RestTemplate put Method :

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:

Spring RestTemplate delete Method :

When you run above code, bhutan will be deleted from list of countries.

You may also like:

 

Was this post helpful?

Leave a Reply

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