415 Unsupported Media Type
用法
收到 415 Unsupported Media Type 错误消息时,成因往往是 Content-Type 或 Content-Encoding 头被服务器拒绝。或者,服务器基于对消息体的进一步检查返回此错误。
在后一种情况下,服务器返回此错误是因为解析或识别内容失败。当服务器识别出媒体类型但不支持该格式时,415 Unsupported Media Type 是最准确的响应。当内容存在结构性错误时,400 或 422 更为合适。
此错误类似于 406,区别在于 415 Unsupported Media Type 基于 Content-Type 和 Content-Encoding 头,而非基于 Accept 头。
SEO 影响
像 Google 这样的搜索引擎不会索引响应状态为 415 的 URL。此前已被索引的 URL 会从搜索结果中移除。
示例
客户端想以纯文本发送一条消息,但由于只接受 HTML 消息,服务器返回 415 Unsupported Media Type。随后客户端更改了 Content-Type 头,但保持原始消息不变。服务器识别出消息体并非有效的 HTML,第二次拒绝了该请求。
初始请求
POST /blog/newmessage HTTP/1.1
Host: example.com
Content-Type: text/plain
Content-Length: 24
Good morning, Everybody!
初始响应,基于 Content-Type 头
HTTP/1.1 415 Unsupported Media Type
Content-Type: text/html
Content-Length: 138
<html>
<head>
<title>Unsupported Format</title>
</head>
<body>
<p>Please use HTML to post new messages.</p>
</body>
</html>
试图绕过校验的后续请求
POST /blog/newmessage HTTP/1.1
Host: example.com
Content-Type: text/html
Content-Length: 24
Good morning, Everybody!
后续响应,基于消息体检查
HTTP/1.1 415 Unsupported Media Type
Content-Type: text/html
Content-Length: 151
<html>
<head>
<title>Unsupported Format</title>
</head>
<body>
<p>No HTML tags found. Use HTML to post messages.
</p>
</body>
</html>
如何修复
核实 Content-Type 头与服务器接受的某种格式相匹配。API 文档通常会列出支持的媒体类型。常见值包括 application/json、application/xml、multipart/form-data 和 application/x-www-form-urlencoded。
消息体内容必须与声明的 Content-Type 相匹配。以 Content-Type: application/json 发送纯文本会失败,因为服务器会尝试将消息体解析为 JSON。有些服务器对字符集写法很严格:在某些平台上,charset=UTF8 而非 charset=UTF-8 会触发拒绝。
发送压缩数据时检查 Content-Encoding 头。声明的编码(如 gzip)与消息体实际的压缩格式不匹配会产生 415。
对于文件上传,确认文件类型在服务器的允许列表中。服务器通常会将上传限制为特定格式,如 JPEG、PNG 或 PDF。
REST API 客户端中的常见错误:
用 Postman 或 curl 之类的工具测试请求,可以隔离出问题是在应用代码中还是在请求本身。当选择了消息体类型时,Postman 会自动设置 Content-Type 头。
代码参考
.NET
HttpStatusCode.UnsupportedMediaType
Rust
http::StatusCode::UNSUPPORTED_MEDIA_TYPE
Rails
:unsupported_media_type
Go
http.StatusUnsupportedMediaType
Symfony
Response::HTTP_UNSUPPORTED_MEDIA_TYPE
Python3.5+
http.HTTPStatus.UNSUPPORTED_MEDIA_TYPE
Java
java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE
Apache HttpComponents Core
org.apache.hc.core5.http.HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE
Angular
@angular/common/http/HttpStatusCode.UnsupportedMediaType