HttpMessageConverters in Spring are used to convert Java Objects to and from JSON, XML, etc in web services.
The ways to determine the response format the client is expecting, is to check “Accept” header value.
E.g. If the client invokes and endpoint say /employees and the Accept header has a value “application/json” , this endpoint will return the list of employees in the JSON format. This is the default format in Spring boot applications.
But what if your client is expecting the response in XML format but your API is not capable to send the response format.
You will get a 406 Not Acceptable response and in the console you will fine below response
2021-04-03 20:53:41.441 WARN 10100 --- [nio-8890-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
The only change that required is to add a dependency which will enable your app to send a XML response.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
I have created a spring boot project just to demonstrate this example. You can download the project from the below github repository.
Leave a Reply