HTTP Content-Type Header:完整指南 (2026)
开发者需要了解的关于 Content-Type 请求头的一切
开始使用 Hypereal 构建
通过单个 API 访问 Kling、Flux、Sora、Veo 等。免费积分开始,扩展到数百万。
无需信用卡 • 10万+ 开发者 • 企业级服务
HTTP Content-Type 请求头:完整指南 (2026)
Content-Type 请求头是最重要的 HTTP 请求头之一。它告诉服务器(或客户端)请求体或响应体中数据的具体类型,以便其了解如何解析和处理这些数据。Content-Type 设置错误会导致一些最常见的 API 错误:415 Unsupported Media Type(不支持的媒体类型)、JSON 格式错误、文件上传失败以及文本乱码。
本指南涵盖了关于 Content-Type 你需要了解的所有内容,从 MIME 类型到主流语言及框架中的实践案例。
什么是 Content-Type 请求头?
Content-Type 请求头是一个 HTTP 实体头部,用于指示资源或请求/响应体中数据的媒体类型(也称为 MIME 类型)。它遵循以下格式:
Content-Type: type/subtype; parameter=value
例如:
Content-Type: application/json; charset=utf-8
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
三个组成部分
| 部分 | 描述 | 示例 |
|---|---|---|
| Type(类型) | 通用类别 | application, text, image, audio, video, multipart |
| Subtype(子类型) | 具体格式 | json, html, png, mp4, form-data |
| Parameters(参数) | 可选的元数据 | charset=utf-8, boundary=xxx |
常见的 Content-Type 值
以下是 Web 开发和 API 中最常用的 Content-Type 值参考表:
文本类型 (Text Types)
| Content-Type | 用途 |
|---|---|
text/plain |
无格式的纯文本 |
text/html |
HTML 文档 |
text/css |
CSS 样式表 |
text/javascript |
JavaScript 文件 |
text/csv |
逗号分隔值文件 |
text/xml |
XML 文档(推荐使用 application/xml) |
应用程序类型 (Application Types)
| Content-Type | 用途 |
|---|---|
application/json |
JSON 数据(API 最常用) |
application/xml |
XML 数据 |
application/x-www-form-urlencoded |
HTML 表单数据(默认值) |
application/octet-stream |
二进制数据(通用) |
application/pdf |
PDF 文档 |
application/zip |
ZIP 压缩包 |
application/gzip |
Gzip 压缩数据 |
application/graphql+json |
GraphQL 请求 |
多部分类型 (Multipart Types)
| Content-Type | 用途 |
|---|---|
multipart/form-data |
文件上传及包含文件的表单数据 |
multipart/mixed |
单个消息中包含混合内容类型 |
multipart/alternative |
同一内容的不同格式(常用于电子邮件) |
图像类型 (Image Types)
| Content-Type | 用途 |
|---|---|
image/png |
PNG 图像 |
image/jpeg |
JPEG 图像 |
image/gif |
GIF 图像 |
image/webp |
WebP 图像 |
image/svg+xml |
SVG 矢量图 |
image/avif |
AVIF 图像 |
音视频类型 (Audio and Video Types)
| Content-Type | 用途 |
|---|---|
audio/mpeg |
MP3 音频 |
audio/wav |
WAV 音频 |
audio/ogg |
OGG 音频 |
video/mp4 |
MP4 视频 |
video/webm |
WebM 视频 |
何时使用各 Content-Type
application/json
REST API 最常用的 Content-Type。在发送或接收结构化数据时使用。
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}'
application/x-www-form-urlencoded
HTML <form> 提交的默认 Content-Type。数据被编码为以 & 分隔的键值对。
curl -X POST https://api.example.com/login \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=john&password=secret123"
请求体中的数据如下所示:
username=john&password=secret123
特殊字符会进行百分比编码(例如,空格变为 + 或 %20)。
multipart/form-data
文件上传时必需。每个字段作为一个独立的部分发送,并拥有自己的 Content-Type。
curl -X POST https://api.example.com/upload \
-H "Content-Type: multipart/form-data" \
-F "file=@photo.jpg" \
-F "description=My vacation photo"
在不同语言中设置 Content-Type
JavaScript (Fetch API)
// JSON 请求
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'John', email: 'john@example.com' }),
});
// 表单数据 (Content-Type 会自动设置)
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('name', 'John');
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
// 不要为 FormData 手动设置 Content-Type
// 浏览器会自动设置并包含正确的 boundary(边界字符串)
body: formData,
});
Python (Requests)
import requests
# JSON 请求 (使用 json= 参数会自动设置 Content-Type)
response = requests.post(
'https://api.example.com/data',
json={'name': 'John', 'email': 'john@example.com'}
)
# 表单编码 (使用 data= 参数会自动设置)
response = requests.post(
'https://api.example.com/login',
data={'username': 'john', 'password': 'secret123'}
)
# 文件上传 (使用 files= 参数会自动设置 Content-Type)
with open('photo.jpg', 'rb') as f:
response = requests.post(
'https://api.example.com/upload',
files={'file': ('photo.jpg', f, 'image/jpeg')},
data={'description': 'My vacation photo'}
)
# 显式设置 Content-Type
response = requests.post(
'https://api.example.com/data',
headers={'Content-Type': 'application/xml'},
data='<user><name>John</name></user>'
)
Go
package main
import (
"bytes"
"encoding/json"
"net/http"
)
func main() {
// JSON 请求
data := map[string]string{"name": "John", "email": "john@example.com"}
jsonData, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", "https://api.example.com/data",
bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
}
cURL
# JSON
curl -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d '{"name": "John"}'
# 表单数据
curl -X POST https://api.example.com/login \
-d "username=john&password=secret"
# 文件上传
curl -X POST https://api.example.com/upload \
-F "file=@photo.jpg" \
-F "description=My photo"
# 二进制数据
curl -X POST https://api.example.com/binary \
-H "Content-Type: application/octet-stream" \
--data-binary @file.bin
API 响应中的 Content-Type
服务器也必须在响应中设置正确的 Content-Type,以便客户端知道如何解析数据。
Express.js
app.get('/api/users', (req, res) => {
// res.json() 会自动设置 Content-Type: application/json
res.json({ users: [] });
});
app.get('/report.pdf', (req, res) => {
res.setHeader('Content-Type', 'application/pdf');
res.sendFile('/path/to/report.pdf');
});
app.get('/page', (req, res) => {
// 对字符串使用 res.send() 会设置 Content-Type: text/html
res.send('<h1>Hello</h1>');
});
FastAPI (Python)
from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse, StreamingResponse
app = FastAPI()
@app.get("/api/users")
async def get_users():
# 默认返回 application/json
return {"users": []}
@app.get("/page", response_class=HTMLResponse)
async def get_page():
return "<h1>Hello</h1>"
@app.get("/download")
async def download_file():
return StreamingResponse(
open("file.pdf", "rb"),
media_type="application/pdf"
)
charset 参数
charset 参数指定了文本内容的字符编码。UTF-8 是标准编码,除非有特殊原因,否则应始终使用它:
Content-Type: text/html; charset=utf-8
Content-Type: application/json; charset=utf-8
注意:JSON 规范 (RFC 8259) 规定 JSON 必须使用 UTF-8 编码。从技术上讲,对于 application/json 来说 charset 参数是不必要的,但许多 API 为了清晰起见仍会包含它。
Content-Type 与 Accept 请求头的区别
这两个请求头经常被混淆:
| 请求头 | 用途 | 使用场景 | 方向 |
|---|---|---|---|
Content-Type |
描述正文格式 | 请求与响应 | “这是我发送的内容” |
Accept |
请求特定的格式 | 仅限请求 | “这是我想要接收的内容” |
# “我正在发送 JSON,并且希望返回 JSON”
curl -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"name": "John"}'
常见错误及解决方法
415 Unsupported Media Type
服务器不接受你发送的 Content-Type。
# 错误:向仅支持 JSON 的端点发送表单数据
curl -X POST https://api.example.com/data \
-d "name=John"
# 解决:改为发送 JSON
curl -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d '{"name": "John"}'
400 Bad Request (Malformed JSON)
Content-Type 声明为 JSON,但请求体不是有效的 JSON。
# 错误:非有效的 JSON
curl -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d "name=John"
# 解决:使用正确的 JSON 语法
curl -X POST https://api.example.com/data \
-H "Content-Type: application/json" \
-d '{"name": "John"}'
使用 FormData 时文件上传失败
在 JavaScript 中使用 FormData 时,不要手动设置 Content-Type。浏览器需要自行设置它以包含正确的 boundary 字符串。
// 错误示例
const formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' }, // 千万不要这样做
body: formData,
});
// 正确示例
fetch('/upload', {
method: 'POST',
// 让浏览器自动设置带有 boundary 的 Content-Type
body: formData,
});
内容协商 (Content Negotiation)
某些 API 支持多种响应格式。客户端使用 Accept 请求头来请求特定格式,服务器在响应中使用 Content-Type 来确认其实际发送的格式:
# 请求 XML 响应
curl -H "Accept: application/xml" https://api.example.com/users
# 请求 JSON 响应
curl -H "Accept: application/json" https://api.example.com/users
总结
Content-Type 请求头是 HTTP 通信运作的基础。正确设置它可以确保服务器和客户端能够正确解析数据,保证文件上传正常运行,并使 API 返回正确的格式。大多数现代框架在常见场景(JSON、表单数据)下会自动处理 Content-Type,但了解其工作原理有助于你排查不可避免的边缘情况。
如果你正在构建涉及 AI 生成媒体(图像、视频、音频或数字人)的应用程序,请查看 Hypereal AI。它提供统一的 API,可返回带有正确 Content-Type 请求头的媒体内容,并为你处理所有复杂的底层逻辑。
免费试用 Hypereal AI —— 提供 35 个额度,无需信用卡。
