Wednesday, April 9, 2014

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

This exception is raised when an http converter is not available on the classpath
In this blog i will show an example to configure Jackson JSON and XStream XML http message converters

Add XStream and Jackson libraries on the classpath
<properties>
<jackson.version>2.2.3</jackson.version>
<xstream.version>1.4.6</xstream.version>
</properties>

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
</dependencies>


Make sure Spring OXM is also added on the classpath
<!-- Spring OXM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring-framework.version}</version>
</dependency>

Now extend your WebMVC configuration class with WebMvcConfigurerAdapter and override the configureMessageConverters method to register the XStream XML and Jackson JSON converters
This how your WebMVC Configuration class should look like

@EnableWebMvc
@Configuration
@ComponentScan({ "change.it.your.controllers.package" })
public class WebConfig extends WebMvcConfigurerAdapter {
 
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
messageConverters.add(createXmlHttpMessageConverter());
messageConverters.add(new MappingJackson2HttpMessageConverter());
 
super.configureMessageConverters(converters);
}
private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
MarshallingHttpMessageConverter xmlConverter =
 new MarshallingHttpMessageConverter();
 
XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
 
return xmlConverter;
}
}

You are all done and the converters have been registered to handle XML and JSON rest services

To test use the curl with following headers
FOR XML
"Accept: text/xml"
FOR JSON
"Accept: application/json"
Example:
curl -i -X GET -H "Accept: application/json" http://url-of-you-rest-service/
OR
curl -i -X GET -H "Accept: text/xml" http://url-of-you-rest-service/

No comments:

Post a Comment