Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring REST consumption results in HTTP Status 406 - Not Acceptable

I get this error when i try to consume a REST API:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable

Here's the client code that gets executed:

public static void main(String[] args) {
   Car c = getCarById(4);
   System.out.println(c);
}

public static  @ResponseBody Car getCarById(int id){
    return new RestTemplate().getForObject("http://localhost:8080/rest/cars/{id}", Car.class, id);
}

Here's the code of the Controller which maps the request:

@RequestMapping(value="/cars/{id}", method=RequestMethod.GET, headers = {"Accept=text/html,application/xhtml+xml,application/xml"}, produces="application/xml")
public @ResponseBody Car getCarById(@PathVariable("id") int id){
    return carService.getCarById(id);
}

Why is this error (406-Not Acceptable) happening although the mappers should take care of mapping to the correct types?

like image 698
ndrizza Avatar asked Jul 11 '12 09:07

ndrizza


2 Answers

You're sending an Accept= header instead of an Accept: header.

like image 166
Tom van der Woerdt Avatar answered Oct 18 '22 06:10

Tom van der Woerdt


I got this answer when I had a wrong Accept: header in my request. I was trying to request an image/jpeg, but my request contained "Accept: application/json".

The solution was to use the correct entity class to query for (I was querying for Object just to see what would come), in my case Resource.class.

like image 1
koljaTM Avatar answered Oct 18 '22 07:10

koljaTM