python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python常用的请求方式

Python中常用的请求方式详解(包括JSON、表单及其他常见数据传输格式)

作者:detayun

本文介绍了Python中常用的几种请求数据格式,包括JSON、表单数据、XML等,详细讲解了它们的特点和适用场景,并提供了最佳实践建议,帮助读者根据具体需求选择合适的传输方式,需要的朋友可以参考下

在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

特点:

二、表单格式请求(传统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)

表单格式特点:

三、其他常见请求格式

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值:

五、最佳实践建议

  1. RESTful API:优先使用JSON格式
  2. 传统Web应用:使用表单格式
  3. 文件上传:必须使用multipart格式
  4. 明确响应格式:通过Accept头指定期望的响应类型
  5. 错误处理:始终检查响应状态码
  6. 安全性:敏感数据使用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常用的请求方式的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文