org.springframework.web.HttpMediaTypeNotAcceptable

2019-09-17 10:47发布

Im trying to get json response from my Spring Controller. Im getting below exception

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

I have jackson related jars in pom.xml as below

<properties>
    <spring.version>4.2.5.RELEASE</spring.version>
    <jstl.version>1.2</jstl.version>
    <servletapi.version>2.5</servletapi.version>
    <jackson.version>2.6.3</jackson.version>
</properties>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>

Below is my controller

    @ResponseBody
    @RequestMapping(value = "/getNodes.htm",produces="application/json")
    public List<NodeDTO> getNodes() {
...
return nodes;
}

Im getting 406 error in the browser and above exception in server log. My browser is properly sending Accept header has application/json. But still Im facing this issue. I have gone through many forums none of them resolving my issue. Please help me to resolve it

1条回答
Anthone
2楼-- · 2019-09-17 11:14

Your @RequestMapping annotation is incorrect, in particular the use of the extension .htm.

It should be

@RequestMapping(value = "/getNodes.json",produces="application/json")

or perhaps

@RequestMapping(value = "/getNodes",produces="application/json")

Spring MVC uses the extension of the URL to identify the type of content to return. In your case, you're specifying an extension of .htm, which Spring interprets as HTML. That however conflicts with the produces property of your annotation, which specifies JSON.

It's not clear to me exactly how Spring handles conflicting content types such as this, but if you replace the .htm extension with .json or drop the extension altogether, then you don't need to worry about it.

查看更多
登录 后发表回答