1

I have a jQuery ajax call like this:

            $.ajax({
            type: "post",
            url: url,
            data: JSON.stringify(formSubmit),
            contentType: "application/json",
            dataType: "json",
            success: function(xhr,status) {
                console.log("Return Data:"+xhr.responseText)
            });

My Controller looks like this:

@RequestMapping(value = "/doIt", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody 
public MyObject activityPerformed(HttpServletRequest request, HttpServletResponse response,  @RequestBody String jsonData) {
    logger.debug("JSON INPUT:"+jsonData);
    MyObject o = new MyObject("STUFF");
    return o;
}

This throws a 406 error. I can see in my browser that I have this in my response headers:

Content-Type:"text/html;charset=utf-8"

Which I thought the produces part of the mapping should have fixed.

When I remove the "contentType" of the ajax call, I do not get the 406 error, but then the jsonData parameter in URLEncoded. No I assume that I could do a decode, but that, I think, is not "right".

So how do I send non URL encoded JSON to a controller without the contentType: "application/json" in the ajax call?

OR how do I set the contentType of the controller response?

mmaceachran
  • 3,178
  • 7
  • 53
  • 102
  • Have you checked the server security log? Apache generates the error when the request violates mod_security rules. So it may not be your jsonData request causing the error. – Dexter Mar 31 '16 at 01:35
  • I am using tomcat 8.0.30 – mmaceachran Mar 31 '16 at 01:36
  • Another person with your setup and the same problem: http://stackoverflow.com/questions/7462202/spring-json-request-getting-406-not-acceptable . I'm not sure what your setup is but this may help guide you to the source of the error so you know what details to provide. They're not using the same request headers as you, but the answers may show you what direction to go. – Dexter Mar 31 '16 at 01:40

1 Answers1

0

Spring is the party responsible for sending back the 406. The Spring reference documentation and JavaDoc will help to shed some light on this.

From the reference documentation:

[regarding the produces field] The request will be matched only if the Accept request header matches one of these values.

I would expect you no longer get the 406 HTTP Status Code if you add the proper Accept request header (sec 14.1) (value of application/json;charset=UTF-8) to your ajax request.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120