Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help on RestTemplate postForObject() method

I have to send JSON data from one service method to the other using postForObject() method. I saw one example on RestTemplate on this link.

postForObject() method has the following format:

User returns = rt.postForObject(uri, u, User.class, vars);

Or

User returns = rt.postForObject(uri, u, User.class);

I want to know that, after using postForObject() method, if we implement the service method to accept the User object, how it will look like?

In my project, I have code like

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
String uri = "http://testcode.com/myapp/api/launchservices";
ServiceRequest request = new ServiceRequest();
request.setId(UUID.randomUUID().toString());
....

I am getting error at this line:

ServiceRequest req = restTemplate.postForObject(uri, request, ServiceRequest.class);

while executing this, I am getting this error mesage:

org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:537)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:493)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:452)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:302)

my implementation method is:

@RequestMapping(value = "/launchservices", method = RequestMethod.POST)
@ResponseBody
public boolean launchServices(@PathVariable ServiceRequest request) {
    System.out.println("Request: "+request.toString());
    return true;
}

How to get rid of this? What will be the URI?

like image 648
omjaijagdish Avatar asked Nov 21 '13 06:11

omjaijagdish


1 Answers

I got solution to this problem.

In this example,method postForObject returns an object of class "ServiceRequest"

ServiceRequest req = restTemplate.postForObject(uri, request, ServiceRequest.class);

So, the method that implements this service with the above 'uri' should return an object of class ServiceRequest
All it needs is, slight modification in implementation method as below

@RequestMapping(value = "/launchservices", method = RequestMethod.POST,  headers = "Accept=application/json")
@ResponseBody
public ServiceRequest launchServices(@RequestBody ServiceRequest request) {
    System.out.println("Request: "+request.toString());
    return request;
}
like image 64
omjaijagdish Avatar answered Oct 17 '22 02:10

omjaijagdish