Post xml to Spring REST server returns Unsupported Media Type

I am trying to create a simple spring based web service that supports a "message" with xml content.

In spring, I define AnnotationMethodHandler:

<bean id="inboundMessageAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <util:list> <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> <property name="marshaller" ref="xmlMarshaller"/> <property name="unmarshaller" ref="xmlMarshaller"/> </bean> </util:list> </property> </bean> 

And jaxb based marshaller:

 <bean id="xmlMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="contextPaths"> <array> <value>com.company.schema</value> </array> </property> <property name="schemas"> <array> <value>classpath:core.xsd</value> </array> </property> </bean> 

My controller is annotated as follows, where Resource is a jaxb auto generated class:

 @RequestMapping(method = POST, value = "/resource") public Resource createResource(@RequestBody Resource resource) { // do work } 

The result of the webservice call is always the "HTTP / 1.1 415 Unsupported Media Type". Here is an example of a service call:

 HttpPost post = new HttpPost(uri); post.addHeader("Accept", "application/xml"); post.addHeader("Content-Type", "application/xml"); StringEntity entity = new StringEntity(request, "UTF-8"); entity.setContentType("application/xml"); post.setEntity(entity); 

It seems to me that I am setting the right type of media everywhere. Does anyone have any idea?

Edit: after further debugging, it looks as if it does not come to an attempt to untie the object. I don't quite understand the black magic behind how AnnotationMethodHandler knows that something like application / xml should go into the MarshallingHttpConverter. Can anyone shed some light on this?

+6
java spring rest spring-mvc jaxb
source share
1 answer

The most likely reason is that the JAXB context does not know how to decouple a Resource object.

Is there a Resource @XMLRootElement annotation? If not, then Jaxb2Marshaller will not accept the parameter, and you will get 415 error. This is done by delegating from Sprng to the JAXB runtime, Spring does not really matter much in this matter.

edit . Actual forcing data to the @RequestBody parameter @RequestBody done in HandlerMethodInvoker.resolveRequestBody() . There are many conditions that must be met before a match is made, including matching the MIME type and the type of the parameter class, and if that fails, there is no registration, just HTTP 415. Look at the source of this method, and better yet, do some remote debugging to see where the logic is not working for your installation.

+5
source share

All Articles