Spring MVC应用返回HTTP 415不支持的媒体类型问题求助
解决Spring MVC POST请求返回415 Unsupported Media Type错误
问题场景
开发Spring MVC Web应用时,编写了如下Controller代码:
@RestController @RequestMapping(value ="/certificate", produces = MediaType.APPLICATION_JSON_VALUE) public class GiftCertificateController { private final GiftCertificateService gcs; @Autowired public GiftCertificateController(GiftCertificateService gcs) { this.gcs = gcs; } @PostMapping public ResponseEntity<?> createCertificate(@RequestBody GiftCertificate gc) throws Exception { gcs.createCertificate(gc); return new ResponseEntity<>(Map.of("status", HttpStatus.CREATED), HttpStatus.CREATED); } // some GetMapping and DeleteMapping functions // omitted for simplicity }
通过Postman发送POST请求,携带如下JSON数据:
{ "name": "sas", "description": "sasasas", "price": 12, "duration": 12 }
已将请求的Content-Type设置为application/json,但仍返回HTTP 415 Unsupported Media Type错误。
解决方案
检查Jackson依赖是否存在
Spring Boot项目中,spring-boot-starter-web已包含Jackson相关依赖。如果是纯Spring MVC项目,需手动引入jackson-databind依赖:<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>对应版本号</version> </dependency>校验GiftCertificate实体类结构
- 必须提供无参构造函数,Jackson默认通过无参构造实例化对象;
- 字段需配备对应的getter/setter方法,或使用Lombok的
@Data注解自动生成; - 确保实体类字段名称与JSON请求体中的键完全匹配(大小写敏感),避免拼写错误。
显式指定请求支持的媒体类型
当前@RequestMapping仅设置了produces,可添加consumes属性明确支持的请求格式,或在@PostMapping上单独配置:// 方式1:在@RequestMapping添加consumes @RequestMapping(value ="/certificate", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) // 方式2:在@PostMapping单独设置 @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)检查Postman请求配置
- 确认Content-Type头严格为
application/json,无拼写错误(如application/json;charset=utf-8也是合法格式); - 确认请求体选择
raw格式并指定为JSON,而非form-data或x-www-form-urlencoded。
- 确认Content-Type头严格为
纯Spring MVC场景需配置消息转换器
若未使用Spring Boot,需在Web配置类中注册MappingJackson2HttpMessageConverter,确保Spring能解析JSON请求体:@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MappingJackson2HttpMessageConverter()); } }
内容的提问来源于stack exchange,提问作者Volodymyr Burmus
相关产品推荐
相关产品推荐

