You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot接口接收HTTPie POST请求时遇Unsupported Media Type错误

解决Spring Boot中HTTPie提交JSON文件出现Unsupported Media Type错误

问题原因

你遇到的HttpMediaTypeNotSupportedException是因为HTTPie提交JSON文件时,默认设置的Content-Type为application/octet-stream,而你的Spring Boot接口通过@RequestBody接收参数时,默认只支持application/json类型的请求体,两者不匹配导致解析失败。

解决方案

1. 在HTTPie命令中指定正确的Content-Type

HTTPie提供了快捷参数或显式头来指定Content-Type为application/json:

  • 使用快捷参数-j(自动设置Content-Type并处理JSON):
    http POST http://your-api-url/coffees -j < coffee.json
    
  • 或者显式添加请求头:
    http POST http://your-api-url/coffees Content-Type:application/json < coffee.json
    

2. 显式配置接口支持的媒体类型

在你的@PostMapping注解中添加consumes属性,明确指定接口接收application/json类型的请求体,这会让接口的预期类型更清晰,也能避免后续的类型匹配问题:

import org.springframework.http.MediaType;

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
Coffee postCoffee (@RequestBody Coffee coffee) {
    coffees.add(coffee);
    return coffee;
}

内容的提问来源于stack exchange,提问作者Kris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 02:42:01