Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help on RestTemplate Post Request with Body Parameters?

I have a rest api url and submitted the same as POST request with body (user name, password, other parameters) via Rest Client (restclient-ui-2.4-jar-with-dependencies) and it got worked fine without any issues.

Ex:

URL: https://test.com/cgi-bin/testing/api Body: username=testuser&password=pass123&id=13002&name=raju

The same is not working fine when i used Spring RestTemplate postForObject(url, varmap, Employee.class) method.

Can someone help me with a simple example where the request is a URL, with body parameters and the response is XML which is mapped with a class?

Sample Code:

  MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
  map.add("username", "test");
  map.add("password", "test123");
  map.add("id", "1234");
  MarshallingHttpMessageConverter mc = new MarshallingHttpMessageConverter();
  mc.setMarshaller(new Jaxb2Marshaller());
  mc.setUnmarshaller(new Jaxb2Marshaller());
  list.add(marshallingHttpMessageConverter);
  emediateRestTemplate.setMessageConverters(list);
  Employee employee = (Employee) restTemplate.postForObject(url, map, Employee.class);

Thanks in advance, Kathir

like image 876
Kathir Avatar asked Aug 30 '12 17:08

Kathir


1 Answers

The above converters Ex: "MarshallingHttpMessageConverter" are not required.

MultiValueMap<String, String> parametersMap = new LinkedMultiValueMap<String, String>();
parametersMap.add("username", "test");
parametersMap.add("password", "test123");
parametersMap.add("id", "1234");

For Post:

restTemplate.postForObject(url, parametersMap, Employee.class);
  • url is String - rest api URL
  • parametersMap - MultiValueMap
  • Employee - object which needs to be converted from the JSON response

For Get:

restTemplate.getForObject(url,  class object, variablesMap);
  • url is : String - rest api URL
  • variablesMap - Map
  • class object - object which needs to be converted from the JSON response
like image 153
Kathir Avatar answered Nov 07 '22 13:11

Kathir