postForObject example

In this post under Spring RestTemplate, I will show with example to make a POST http request.

To make a POST http request, Spring RestTemplate framework provides “postForObject” method in “RestTemplate” class.

This method takes 3 arguments, which are
1) url
2) Object to be posted
3) Response type

Below is the complete main code for your reference.

Main class

package package5;
  
 import org.springframework.web.client.RestTemplate;
  
public class Example5 {
      public static void main(String[] args) {
          RestTemplate restTemplate = new RestTemplate();
          String url = "http://jsonplaceholder.typicode.com/posts";
          Post object = new Post();
          object.setTitle("Don");
          object.setBody("Hello");
          object.setUserId(1);
          Post post = restTemplate.postForObject(url, object, Post.class);
          System.out.println(post);
      }
 }

In the above code, at line 7, I create an instance of “RestTemplate” class.

At line 8, I define a url

At line 9, I create an instance of “Post” class and populate its attributes. This will be the data to be send as POST body.

At line 13, I call “postForObject” of “RestTemplate” class instance.

At line 14, I am printing the response body to the console.

In this way we can make a POST http request using Spring RestTemplate.

Leave a comment