In this post under Spring RestTemplate, I will explain with example the purpose of “getForObject” method.
“getForObject” method is provided by RestTemplate to make GET HTTP calls.
Below is the main method showing how to use it
Main class
package package1;
import org.springframework.web.client.RestTemplate;
public class Example1 {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://jsonplaceholder.typicode.com/posts/1";
Post post = restTemplate.getForObject(url, 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 the url to connect to.
At line 9, I call the “getForObject” method passing two parameters
1) the url
2) the class type of the response body
Please note, this method only returns response body. You cannot access headers or status code from this method.
The response body is deserialized to an instance of the class that is passed as argument to “getForObject” method.
The “getForObject” method returns an instance of “Post” class which is printed to console at line 10.
Below is the class structure of “Post” class.
Post
package package1;
public class Post {
private int id;
private String title;
private String body;
private int userId;
//Removed getter and setter for brevity
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(id).append(":");
stringBuilder.append(title).append(":");
stringBuilder.append(body).append(":");
stringBuilder.append(userId);
return stringBuilder.toString();
}
}
In this way we can use “RestTemplate” “getForObject” method to make an GET HTTP call.