postForLocation example

In this post under Spring RestTemplate, I will explain with example the purpose of “postForLocation” method in “RestTemplate” class.

The “postForLocation” method is similar to “postForObject” both are used to perform a POST request.

The only difference is “postForLocation” method returns a url which points to the location where the newly created resource can be found/retrieved.

Below is the complete main class for your reference

Main class

package package6;
  
import org.springframework.web.client.RestTemplate;
  
import java.net.URI;
  
public class Example6 {
      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);
          URI uri = restTemplate.postForLocation(url, object);
          System.out.println(uri);
     }
}

At line 15, we call “postForLocation” method, pass the url and object to be posted and in return we get an “URI” instance.

This URI instance is printed in the next line.

Below is the output

Output

http://jsonplaceholder.typicode.com/posts/101

Leave a comment