我正在尝试使用Spring发布表单数据。该表单数据为XML
格式。但每次我尝试发帖时,都会收到415错误。
public void setFormData(String name, Integer age){
String url = "https://my.example.com/path/";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
Form form = new Form();
form.set("name", name);
form.set("age", age);
HttpEntity<Object> request = new HttpEntity<Object>(form, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(url, request);
}
由于上述方法不起作用,我去实施了这个:
public void setFormData(String name, Integer age){
String url = "https://my.example.com/";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
MultiValueMap<String, Object> params= new LinkedMultiValueMap<String, Object>();
params.add("name", name);
params.add("age", age);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter();
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.APPLICATION_XML);
jaxbMessageConverter.setSupportedMediaTypes(mediaTypes);
messageConverters.add(jaxbMessageConverter);
restTemplate.setMessageConverters(messageConverters);
}
接受请求的XML:
<resource path="/path">
<method name="POST">
<request>
<representation mediaType="application/x-www-form-urlencoded">
<param name="name" style="query" type="xs:string">
<param name="age" style="query" type="xs:int">
</representation>
</request>
</method>
</resource>
但我仍然遇到415错误。我也尝试在Java代码中将MediaType设置为APPLICATION_FORM_URLENCODED
但是我得到415错误。如何使用Spring发布到XML表单?任何帮助将不胜感激。
答案 0 :(得分:0)
ContentType
更改为第一个blob中的APPLICATION_FORM_URLENCODED
。用Http消息转换器混淆的第二代代码是没用的。我不确定您填充的Form
是什么 - MultiValueMap
也应该有用。postForEntity
或postForObject
都应该这样做。