In this post under Spring REST Template, I will show with example how to perform http PUT operation.
For our example I will be updating a “Post” object with id 1 at resource “http://jsonplaceholder.typicode.com/posts”.
Below is the class structure of “Post” class.
Post
package package7;
public class Post {
private int id;
private String title;
private String body;
private int userId;
//Removed the getter, setter and toString for brevity
}
Below is the main class that shows how to perform PUT operation.
Main class
package package7;
import org.springframework.web.client.RestTemplate;
public class Example7 {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://jsonplaceholder.typicode.com/posts/1";
Post object = new Post();
object.setId(1);
object.setTitle("Don");
object.setBody("Hello");
object.setUserId(1);
restTemplate.put(url, object);
}
}
In the above code, at line 7, I create an instance of “RestTemplate” class
At line 8, define the url.
From 9 to 13, created a “Post” object with the data which has to be updated.
At line 14, I call the “put” method available on “RestTemplate” class passing two arguments
1) url
2) object to be posted
In this way we can perform a HTTP PUT method using “RestTemplate” framework.