首页 > 解决方案 > 内容类型不受支持的问题

问题描述

当我发送带有PostmanJSON 正文(application/json)的 post 请求时,我收到了这个错误spring-mvc(我没有使用spring boot

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

我尝试了有关此错误的所有 SO 主题,但没有任何效果:(

Jackson我还包括了pom.xml将 JSON 对象映射到 POJO 的依赖项。

那为什么它一直告诉我Content type 'application/json' not supported

我的控制器

@RestController
public class FooRest {
    // even with consumes=MediaType.APPLICATION_JSON_VALUE it does not work
    @RequestMapping(value = "/api/foo", method = RequestMethod.POST)
    public String foo(HttpServletRequest request, @RequestBody FooBean bean) {
        ...
    }
}

我的配置

@Configuration
@EnableWebMvc
@ComponentScan({"controllers"})
public class AppConfig implements WebMvcConfigurer { }

我的pom.xml

<dependencies>

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


    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

    ...

</dependencies>

卷曲版

POST /MY-API HTTP/1.1
Host: 127.0.0.1:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 89859e26-813d-fb53-8726-57900f02207e

{ 
   //JSON OBJECT
}

解决方案

我变了

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

它终于起作用了:)有人可以解释我为什么吗?

标签: javaspringspring-mvcjackson

解决方案


顺便说一句,@PostMapping@RequestMapping注释的专用版本,用作@RequestMapping(method = RequestMethod.POST).

在Springcontent-negotiation配置(仅当您想以不同的媒体类型(即.@PostMappingapplication/jsonconsumesproduces@PostMappingapplication/xml

因此,以下代码对您应该没问题:

@RestController
public class FooRest {

    @PostMapping("/api/foo")
    public String foo(HttpServletRequest request, @RequestBody FooBean bean) {
        ...
    }
}

最后,您需要accepts请求中的标头作为application/json

你能和我们分享curl你要求的版本吗?


推荐阅读