spring 需要关于带有正文参数的 RestTemplate Post Request 的帮助?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12202729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need help on RestTemplate Post Request with Body Parameters?
提问by Kathir
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.
我有一个rest api url,并通过Rest Client(restclient-ui-2.4-jar-with-dependencies)提交了与带有正文(用户名、密码、其他参数)的POST请求相同的请求,并且它运行良好,没有任何问题。
Ex:
前任:
URL: https://test.com/cgi-bin/testing/apiBody: username=testuser&password=pass123&id=13002&name=raju
网址:https://test.com/cgi-bin/testing/api 正文: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.
当我使用 Spring RestTemplate postForObject(url, varmap, Employee.class) 方法时,同样无法正常工作。
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?
有人可以帮我举一个简单的例子,其中请求是一个 URL,带有正文参数,响应是用类映射的 XML?
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
提前致谢,凯瑟
回答by Kathir
The above converters Ex: "MarshallingHttpMessageConverter" are not required.
上述转换器例如:“MarshallingHttpMessageConverter”不是必需的。
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
- url 是 String - rest api URL
- 参数映射 - 多值映射
- Employee - 需要从 JSON 响应转换的对象
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
- url 是:字符串 - 休息 api URL
- variablesMap - 地图
- 类对象 - 需要从 JSON 响应转换的对象

