Spring: Getting HTTP 406 from a REST controller

You may get a HTTP 406 Inacceptable 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 he 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<Dog> 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
<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-core-asl</artifactId>
	<version>1.9.13</version>
</dependency>

<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.9.13</version>
</dependency>
Spring version >= 3.1.2 RELEASE
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.6</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>

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 )

    Twitter picture

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

    Facebook photo

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

    Google+ photo

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

    Connecting to %s