Spring Restful client – RestTemplate example

Previous
Next

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:

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.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog