Spring: Getting HTTP 406 from a REST controller

You may get a HTTP 406 Not Acceptable error while trying to return Java objects from a REST controller.

The server is not able to handle your request because the HTTP header “Accept” does not match with any of the content types it can handle.

In fact, the server might be unable to deliver the response in whatever content-type, some piece of configuration is missing in your project.

Example

Let’s declare a “GET /dogs” method in your Spring @Controller:

@RequestMapping(value = "/dogs", method = RequestMethod.GET)
@ResponseBody
public List getDogs() {
  return this.dogRepository.getAllDogs();
}

Using Spring you have to declare a mapper in order to tell Spring how to convert Java POJO to whatever content type.
Let’s say you want to convert your POJOs to JSON, so you have to use a JSON Mapper.

Maven dependencies to add

Spring version = 3.1.2.RELEASE

	org.codehaus.jackson
	jackson-core-asl
	1.9.13



	org.codehaus.jackson
	jackson-mapper-asl
	1.9.13

Spring version >= 3.1.2 RELEASE

    com.fasterxml.jackson.core
    jackson-core
    2.8.6



    com.fasterxml.jackson.core
    jackson-databind
    2.8.6

Just redeploy your webapp and you’ll be able to get your Java POJO as a JSON object.

Side notes:
  • You can use the class annotation @RestController to avoid adding method annotation @ResponseBody
  • HTTP 406 RFC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.