Python中常用的请求方式详解(包括JSON、表单及其他常见数据传输格式)
在Python中进行网络请求时,数据传输格式的选择直接影响着API交互的效率和可靠性。本文将详细介绍Python中常用的请求数据格式,包括JSON、表单数据以及其他常见格式,帮助你根据不同场景选择最合适的传输方式。
一、JSON格式请求(最常用)
JSON(JavaScript Object Notation)是现代Web开发中最流行的数据交换格式,具有轻量级、易读、跨语言支持等优点。
使用requests库发送JSON请求
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. 普通表单提交
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格式:
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:
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. 原始文本请求
适用于纯文本数据传输:
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. 二进制数据请求
直接传输二进制数据(如图片、音频等):
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)对于数据传输至关重要:
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- 二进制流
五、最佳实践建议
- RESTful API:优先使用JSON格式
- 传统Web应用:使用表单格式
- 文件上传:必须使用multipart格式
- 明确响应格式:通过Accept头指定期望的响应类型
- 错误处理:始终检查响应状态码
- 安全性:敏感数据使用HTTPS传输
六、完整示例对比
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应用中仍然普遍存在。根据具体场景选择合适的请求格式,并正确设置请求头,可以确保你的网络请求高效可靠地完成数据传输任务。
以上就是Python中常用的请求方式详解(包括JSON、表单及其他常见数据传输格式)的详细内容,更多关于Python常用的请求方式的资料请关注脚本之家其它相关文章!
相关文章
TensorFlow实现checkpoint文件转换为pb文件
今天小编就为大家分享一篇TensorFlow实现checkpoint文件转换为pb文件,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-02-02
Python列表排序方法reverse、sort、sorted详解
这篇文章主要介绍了Python列表排序方法reverse、sort、sorted详解,需要的朋友可以参考下2021-04-04
pandas数据选取:df[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[]
这篇文章主要介绍了pandas数据选取:df[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[],文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-04-04


最新评论