Spring-MVC 406 Not Acceptable instead of JSON Response

后端 未结 5 1986
天涯浪人
天涯浪人 2020-12-03 08:02

I\'m trying to return a JSON response with Spring 3.0.6, but I get a 406 response \"Not Acceptable\", with the description: \"The resource identified by this request is onl

相关标签:
5条回答
  • 2020-12-03 08:37

    I ran into this problem because the objects that I wanted to return as JSON didn't have any getter methods for their properties. Jackson probably needs these. After adding them it worked.

    0 讨论(0)
  • 2020-12-03 08:42

    although this thread is a little old...

    u need to add the following (maven dependency):

    org.codehaus.jacksonjackson-mapper-asl1.9.13

    0 讨论(0)
  • 2020-12-03 08:43

    In terms of the MappingJacksonJson processing, you'll need to make sure that the Jackson ObjectMapper supports your object type for serialisation.

    0 讨论(0)
  • 2020-12-03 08:49

    Add the following in DispatcherServlet-servlet.xml.

    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter"/>
            </list>
        </property>
    </bean>
    
    0 讨论(0)
  • 2020-12-03 09:00

    I've stumbled upon the same error (406: content not acceptable) with Spring MVC and @RestController annotation.

    The Spring handler:

    @RequestMapping(value = "/stuff-acknowledgment/{id}", produces ="application/json;charset=UTF-8", headers="Accept=*")
    public Message acknowledgeStuff(@PathVariable("id") String id, @ModelAttribute("ack") AckBean acquittement) {
    

    Observation:

    • the URI has the form : http://www.host.com/stuff-acknowledgment/{id}
    • BUT $id has a very particular format: xxxcomplicatedhashxxx.png (or whatever extension you can think of).

    Therefore:

    Spring MVC interpret the extension and want to produce a result of that same mime type (even if I define it as a path variable), here an "image/png" MIME type even if I tell him to produce JSON. So a 406 exception is thrown.

    Fix:

    Remove the ".png" extension in the URI, or remove the PathVariable and put it in the body, or add a suffix behind the pathVariable (not tested but should work as well), the point is to avoid a file extension at the end of the URI.

    P.S.: I know it doesn't answer the specific problem (with the solution in the update) in the question but I found that SO thread when searching for that problem and post my fix here for the record, hoping it can help someone in the future.

    0 讨论(0)
提交回复
热议问题