Need help on RestTemplate Post Request with Body Parameters?

徘徊边缘 提交于 2019-12-06 22:51:16

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/12202729/need-help-on-resttemplate-post-request-with-body-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!