Search code examples
springlistrestspring-mvchttp-status-code-406

406 Not Acceptable for List - REST


I am trying to find a way instead of Wrapper class but I always get 406 Not Acceptable error. I searched online and tried many different ways but couldn't fix it.

@RequestMapping(value = "/users/getlist", headers="Accept=application/xml, application/json", method=RequestMethod.POST)
public @ResponseBody List<Permission> getList(@RequestParam String userEmail) {         
    List<Permission> permissions = service.getPermissions(userEmail);

      return permissions;
}

And

MultiValueMap<String, String> userMap = new LinkedMultiValueMap<String, String>();
userMap.add("userEmail", email_address);

// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);

// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<?> userEntity = new HttpEntity<Object>(userMap, headers);

List<Permission> permissions = restTemplate.postForObject("http://localhost:8080/users/getlist", userEntity, List.class);

I also tried;

List<Permission> permissions = (List<Permission>) restTemplate.postForEntity("http://localhost:8080/users/getlist", userEntity, List.class);    

So basically if I use a wrapper class with getter and setter, it works. But i need to create many wrapper classes. Do you have any idea to implement like this?

SOLUTION:

Worked adding no mediatype to the http entity.


Solution

  • I believe that

    headers="Accept=application/xml, application/json"
    

    will require that your Accept header actually has the value application/xml, application/json. Your request doesn't.

    You add a single acceptable media type.

    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_XML);
    

    That will end up with a request header like

    Accept: application/xml
    

    Which won't match the @RequestMapping declared.

    Instead, if you want the headers to match either application/xml or application/json, you can do

    headers= {"Accept=application/xml", "Accept=application/json"}
    

    or better yet

    produces = {"application/xml", "application/json"}