java - 内容类型不受支持的问题
问题描述
当我发送带有Postman
JSON 正文(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>
它终于起作用了:)有人可以解释我为什么吗?
解决方案
顺便说一句,@PostMapping
是@RequestMapping
注释的专用版本,用作@RequestMapping(method = RequestMethod.POST)
.
在Springcontent-negotiation
配置(仅当您想以不同的媒体类型(即.@PostMapping
application/json
consumes
produces
@PostMapping
application/xml
因此,以下代码对您应该没问题:
@RestController
public class FooRest {
@PostMapping("/api/foo")
public String foo(HttpServletRequest request, @RequestBody FooBean bean) {
...
}
}
最后,您需要accepts
请求中的标头作为application/json
你能和我们分享curl
你要求的版本吗?
推荐阅读
- flash - 没有 Adobe Flash Player 的投影仪内嵌入视频
- wolfram-mathematica - ListPlot:数据不是数字或数字对的列表
- javascript - 无法将 Firebase 实时数据库中的数据检索到 Web 应用程序中
- azure-devops - 如何获取谁/何时更改了 vsts 中的工作项类型?
- python - 无法在 CloudML (1.8) 上保存 Keras 检查点错误:ImportError: `save_model` requires h5py
- visual-studio - 独立 IntelliTrace 收集的记录仅显示外部代码
- javascript - 在 three.js 中使用点云创建平面网格
- java - 如何调用返回 Observable 的多个 API
并将他们的响应汇总到单个对象 - c - C 使用 getline 忽略换行符 \n
- r - 将数据帧子集到 R 中的“最佳正方形”的函数