Python请求方式介绍:JSON、表单及其他常见数据传输格式

在Python中进行网络请求时,数据传输格式的选择直接影响着API交互的效率和可靠性。本文将详细介绍Python中常用的请求数据格式,包括JSON、表单数据以及其他常见格式,帮助你根据不同场景选择最合适的传输方式。

一、JSON格式请求(最常用)

JSON(JavaScript Object Notation)是现代Web开发中最流行的数据交换格式,具有轻量级、易读、跨语言支持等优点。

使用requests库发送JSON请求

python 复制代码
import requests
import json

url = "https://example.com/api"
data = {
    "name": "张三",
    "age": 30,
    "skills": ["Python", "Web开发"]
}

# 方法1:直接使用json参数(推荐)
response = requests.post(url, json=data)

# 方法2:手动转换为JSON字符串
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)

print(response.status_code)
print(response.json())  # 解析响应JSON

特点:

  • 自动设置Content-Type: application/json
  • 自动处理Python字典与JSON字符串的转换
  • 适合复杂数据结构传输
  • 大多数RESTful API的首选格式

二、表单格式请求(传统Web表单)

表单格式(application/x-www-form-urlencoded)是HTML表单默认的提交方式。

1. 普通表单提交

python 复制代码
import requests

url = "https://example.com/login"
form_data = {
    "username": "user123",
    "password": "secure123"
}

response = requests.post(url, data=form_data)

# 自动设置Content-Type: application/x-www-form-urlencoded
print(response.text)

2. 多部分表单(文件上传)

当需要上传文件时,应使用multipart/form-data格式:

python 复制代码
import requests

url = "https://example.com/upload"
files = {
    'file': ('report.pdf', open('report.pdf', 'rb'), 'application/pdf'),
    'description': ('', 'Monthly report')  # 可包含普通字段
}

response = requests.post(url, files=files)
print(response.status_code)

表单格式特点:

  • 简单键值对结构
  • 适合传统Web应用
  • 文件上传必须使用multipart格式
  • 自动编码特殊字符(如空格转为+

三、其他常见请求格式

1. XML格式请求

虽然不如JSON流行,但某些遗留系统仍使用XML:

python 复制代码
import requests

url = "https://example.com/api"
xml_data = """
<user>
    <name>李四</name>
    <age>25</age>
</user>
"""

headers = {'Content-Type': 'application/xml'}
response = requests.post(url, data=xml_data, headers=headers)
print(response.text)

2. 原始文本请求

适用于纯文本数据传输:

python 复制代码
import requests

url = "https://example.com/process"
text_data = "This is plain text data"

headers = {'Content-Type': 'text/plain'}
response = requests.post(url, data=text_data, headers=headers)
print(response.status_code)

3. 二进制数据请求

直接传输二进制数据(如图片、音频等):

python 复制代码
import requests

url = "https://example.com/process-image"
with open('image.jpg', 'rb') as f:
    binary_data = f.read()

headers = {'Content-Type': 'application/octet-stream'}
response = requests.post(url, data=binary_data, headers=headers)
print(response.headers)

四、请求头与内容类型

正确设置请求头(Headers)对于数据传输至关重要:

python 复制代码
headers = {
    'Content-Type': 'application/json',  # 指定发送数据的格式
    'Accept': 'application/json',       # 指定希望接收的响应格式
    'Authorization': 'Bearer token123'  # 认证信息
}

response = requests.get(url, headers=headers)

常见Content-Type值:

  • application/json - JSON格式
  • application/x-www-form-urlencoded - 普通表单
  • multipart/form-data - 带文件的表单
  • application/xml - XML格式
  • text/plain - 纯文本
  • application/octet-stream - 二进制流

五、最佳实践建议

  1. RESTful API:优先使用JSON格式
  2. 传统Web应用:使用表单格式
  3. 文件上传:必须使用multipart格式
  4. 明确响应格式:通过Accept头指定期望的响应类型
  5. 错误处理:始终检查响应状态码
  6. 安全性:敏感数据使用HTTPS传输

六、完整示例对比

python 复制代码
import requests
import json

base_url = "https://example.com/api"

# JSON请求示例
def json_request():
    data = {"key": "value"}
    response = requests.post(f"{base_url}/json", json=data)
    print("JSON响应:", response.json())

# 表单请求示例
def form_request():
    data = {"username": "test", "password": "123"}
    response = requests.post(f"{base_url}/form", data=data)
    print("表单响应:", response.text)

# 文件上传示例
def file_upload():
    with open('test.txt', 'rb') as f:
        files = {'file': f}
        response = requests.post(f"{base_url}/upload", files=files)
    print("上传响应状态:", response.status_code)

if __name__ == "__main__":
    json_request()
    form_request()
    file_upload()

总结

Python的requests库提供了灵活的方式来处理各种数据格式的请求。JSON因其简洁和易用性成为现代API的首选,而表单格式在传统Web应用中仍然普遍存在。根据具体场景选择合适的请求格式,并正确设置请求头,可以确保你的网络请求高效可靠地完成数据传输任务。

相关推荐
程序员小八7772 小时前
MySQL 事务:一文把 ACID、隔离级别、MVCC、锁全串起来
数据库·mysql
lzhdim2 小时前
提高 SQL 语句执行速度的方法
java·开发语言·数据库·sql·oracle
小陈的进阶之路2 小时前
Claude Code辅助测试:导入篇skills
python·自动化
ltl2 小时前
ClickHouse Distributed 引擎与分布式查询路由
数据库
Wang's Blog2 小时前
PostgreSQL笔记60: 权限与角色管理——从层级体系到最佳实践
数据库·笔记·postgresql
whcyhhh3 小时前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
for_ever_love__4 小时前
python基础语法学习: 闭包
开发语言·python·学习·闭包
ly76894 小时前
Python 全面入门:从核心语法到工程实践
开发语言·python
龙虾PRO4 小时前
大模型稳定输出 JSON 的四层防线:2026 生产环境落地避坑指南
json
Elastic 中国社区官方博客4 小时前
让大模型思考,让小模型执行:在 Elastic Workflows 中拆分 LLM 成本
大数据·运维·数据库·人工智能·elasticsearch·ai