How do I pass in an object to a RestTemplate
? I currently have an object that I am trying to pass in to two different functions. In one way, I want to pass it in as a RequestBody
, and in the other I want to pass it in as a RequestParam
.
For example, I have the following code:
Student student = new Student("Allison");
Teacher response = restTemplate.getForObject("url for get student's teacher api/{schoolID}", Teacher.class, student);
The getStudentsTeacher
takes in paramters (@PathVariable schoolID, @RequestBody Student student)
.
My code does not work, as I am not specifying the content type (json), so how would I do this? Also, how would this work with @RequestParam
instead of @RequestBody
?
According to the RestTemplate javadoc , the uri variables can be expanded. So, all you need to do, is to supply to value to expand the variable in the template
Teacher response = restTemplate.getForObject("domain.com/api/{schoolId}", Teacher.class, 123);
Now, it's really strange that you're sending a GET request with body. If you really need to do so, then you'll have to use the RestTemplate#exchange method.
HttpEntity<Student> request = new HttpEntity<Student>(new Student("Allison"));
// 123 -> it's the schoolId that the exchange method will be using to expand the uri variable
ResponseEntity<Teacher> teacher = restTemplate.exchange("domain.com/api/{schoolId}", HttpMethod.GET, request, Teacher.class, 123);
log.info(teacher.getBody());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.