使用 HTTP 发送数据时,常见的数据格式主要通过请求头中的 **`Content-Type`** 字段指定。以下是主流的数据格式及示例:
---
### 1. **`application/x-www-form-urlencoded`**
**用途**:默认表单提交格式
**数据格式**:`key1=value1&key2=value2`(URL 编码)
**示例(Python requests)**:
```python
import requests
data = {"username": "john", "password": "secret"}
response = requests.post("https://api.example.com/login", data=data)
```
---
### 2. **`application/json`**
**用途**:REST API 主流格式,支持复杂数据结构
**数据格式**:`{"key": "value"}`
**示例(Python requests)**:
```python
import requests
payload = {"name": "Alice", "age": 30, "hobbies": ["coding", "hiking"]}
headers = {"Content-Type": "application/json"}
response = requests.post("https://api.example.com/users", json=payload, headers=headers)
# 或直接使用 `json` 参数(自动设置头部):
response = requests.post("https://api.example.com/users", json=payload)
```
---
### 3. **`multipart/form-data`**
**用途**:表单含文件上传时使用
**数据格式**:分 boundary 分隔的多部分数据
**示例(Python 上传文件)**:
```python
files = {"file": ("report.pdf", open("report.pdf", "rb"), "application/pdf")}
data = {"user": "admin"}
response = requests.post("https://api.example.com/upload", files=files, data=data)
```
---
### 4. **`text/plain`**
**用途**:发送纯文本
**数据格式**:`This is raw text`
**示例(curl)**:
```bash
curl -X POST -H "Content-Type: text/plain" -d "Hello World" https://api.example.com/log
```
---
### 5. **`application/xml` 或 `text/xml`**
**用途**:传统系统或 SOAP 协议
**数据格式**:
```xml
John
123
```
**示例**:
```python
xml_data = """John123"""
headers = {"Content-Type": "application/xml"}
response = requests.post("https://api.example.com/xml", data=xml_data, headers=headers)
```
---
### 6. **`application/octet-stream`**
**用途**:二进制文件(如图片、压缩包)
**示例(Python 发送二进制数据)**:
```python
with open("image.png", "rb") as f:
binary_data = f.read()
headers = {"Content-Type": "application/octet-stream"}
response = requests.post("https://api.example.com/upload-bin", data=binary_data, headers=headers)
```
---
### 关键注意事项:
1. **请求头**:必须正确设置 `Content-Type`,否则服务端无法解析数据。
2. **编码**:
- JSON/XML 需确保字符编码一致(如 UTF-8)。
- 表单数据会自动 URL 编码。
3. **工具选择**:
- 表单/文件:用 `data` 或 `files` 参数(Python requests)。
- JSON:直接使用 `json` 参数。
- 二进制:传递 `bytes` 类型数据。
---
### 调试工具推荐:
- **cURL**:终端调试
```bash
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com
```
- **Postman**:图形化界面测试 API
- **浏览器开发者工具**:查看网络请求的 Headers 和 Payload
根据目标 API 的要求选择合适的数据格式即可。