HTTP Content-Type介绍(x-www-form-urlencoded、multipart/form-data、text/plain、text/html、octet-stream)内容类型
文章目录一文搞懂 HTTP Content-Type一、什么是 Content-Type二、为什么 Content-Type 很重要三、常见 Content-Type 类型1. application/json最常用2. application/x-www-form-urlencoded3. multipart/form-data4. text/plain5. text/html6. application/xml7. application/octet-stream四、请求 vs 响应中的 Content-Type1. 请求中的 Content-Type2. 响应中的 Content-Type五、Content-Type vs Accept六、常见坑点1. 忘记设置 Content-Type2. JSON 写成 form3. 字符编码问题4. 文件上传必须用 multipart/form-data七、实际开发建议1. 统一使用 JSON推荐2. 接口文档必须写清楚3. 后端要做容错处理八、总结一文搞懂 HTTP Content-Type在日常开发中我们几乎每天都会接触 HTTP 协议而Content-Type是其中最基础却又最容易被忽视的一个字段。很多接口问题、乱码问题、跨语言调用问题其实都和它有关。这篇文章带你彻底搞懂Content-Type的作用、常见类型以及实际开发中的注意事项。一、什么是 Content-TypeContent-Type是 HTTP 头Header中的一个字段用来指明请求或响应体的数据类型媒体类型MIME type。简单来说它回答的是一个问题 “这段数据是什么格式”例如Content-Type: application/json表示 Body 中的数据是 JSON 格式。二、为什么 Content-Type 很重要如果没有Content-Type接收方就无法正确解析数据。举个例子你发送的是 JSON但没写Content-Type服务端可能按表单格式解析结果解析失败 / 参数为空 / 报错 本质上就是“协议不一致”。三、常见 Content-Type 类型1. application/json最常用Content-Type: application/json用于传输 JSON 数据{name:Tom,age:20} 使用场景RESTful API微服务通信前后端分离2. application/x-www-form-urlencodedContent-Type: application/x-www-form-urlencoded数据格式类似 URL 参数nameTomage20 使用场景HTML 表单默认提交方式传统 Web 应用3. multipart/form-dataContent-Type: multipart/form-data; boundary----WebKitFormBoundary用于上传文件------boundary Content-Disposition: form-data; namefile; filenamea.txt Content-Type: text/plain (file content) 使用场景文件上传图片上传4. text/plainContent-Type: text/plain表示纯文本Hello World 使用场景简单文本接口调试接口5. text/htmlContent-Type: text/html表示 HTML 页面h1Hello/h1 使用场景浏览器页面响应6. application/xmlContent-Type: application/xml用于 XML 数据usernameTom/name/user 使用场景老系统SOAP 服务7. application/octet-streamContent-Type: application/octet-stream表示二进制数据通用类型 使用场景文件下载不确定类型的数据四、请求 vs 响应中的 Content-Type1. 请求中的 Content-Type 告诉服务器我发送的数据是什么格式例如POST /api/user Content-Type: application/json2. 响应中的 Content-Type 告诉客户端你收到的数据是什么格式例如HTTP/1.1 200 OK Content-Type: application/json五、Content-Type vs Accept很多人会混淆这两个字段。Header作用Content-Type我发送的是什么Accept我希望接收什么示例Accept: application/json表示客户端希望服务器返回 JSON。六、常见坑点1. 忘记设置 Content-Type表现后端收不到参数JSON 解析失败2. JSON 写成 form错误Content-Type: application/x-www-form-urlencoded但 Body 是 JSON{name:Tom} 一定会解析失败3. 字符编码问题Content-Type: text/html; charsetUTF-8如果不指定 charset可能导致乱码。4. 文件上传必须用 multipart/form-data很多人误用application/json 文件上传一定要用multipart/form-data七、实际开发建议1. 统一使用 JSON推荐现代系统建议统一Content-Type: application/json优点可读性强跨语言支持好与 RESTful 风格一致2. 接口文档必须写清楚比如Content-Type:application/json否则调用方容易踩坑。3. 后端要做容错处理例如自动识别 JSON / form给出清晰错误提示八、总结一句话总结Content-Type 决定了数据如何被解析。记住三点就够了它定义数据格式请求和响应都可以使用错了就会解析失败