python实现http post四种请求体详解
作者:AZ-直到世界的尽头
在HTTP协议中,POST请求通常用于向服务器提交数据。虽然协议本身不强制规定数据的编码方式,但实际开发中形成了四种常见的Content-Type格式:
- application/x-www-form-urlencoded(表单提交)
- multipart/form-data(文件上传)
- application/json(JSON数据)
- text/xml(XML数据)
本文将结合Python代码(同时涵盖传统urllib2和现代requests库),详细演示如何实现这四种请求体。
一、四种请求体格式简介
根据参考资料中的描述:
- application/x-www-form-urlencoded:浏览器原生表单默认格式,数据被编码为键值对(如
key1=value1&key2=value2)。 - multipart/form-data:用于文件上传,数据被分为多个部分,每部分包含字段名和内容,由边界符(boundary)分隔。
- application/json:将数据结构序列化为JSON字符串,目前最流行的API数据交换格式。
- text/xml:基于XML的远程调用规范(如XML-RPC),数据以XML格式包裹。
二、环境准备
我们将使用Python 3.x进行演示。如果使用现代开发,推荐安装第三方库requests(更简洁):
pip install requests
若使用传统方法,需注意Python 3中urllib2已拆分为urllib.request和urllib.error。
三、代码实现
1. application/x-www-form-urlencoded
特点:数据格式为field1=value1&field2=value2,需进行URL编码。
# 方法一:使用内置库 urllib(Python 3)
import urllib.parse
import urllib.request
url = "http://httpbin.org/post"
data = {"package": "com.tencent.lian", "version_code": "66"}
# 将字典编码为application/x-www-form-urlencoded格式
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data=encoded_data, method='POST')
# 设置Content-Type头(可选,urllib会根据data类型自动设置)
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
with urllib.request.urlopen(req) as response:
print(response.read().decode('utf-8'))
# 方法二(推荐):使用 requests 库
import requests
response = requests.post(url, data=data) # 使用data参数
print(response.json())2. multipart/form-data
特点:用于表单混合数据(含文件),每个字段由boundary分隔。
参考资料中使用的是poster模块,但现代Python更推荐使用requests直接处理。
# 方法一:使用requests(推荐)
import requests
url = "http://httpbin.org/post"
# 普通字段
data = {"package": "com.tencent.lian", "version_code": "66"}
# 文件字段
files = {
'file': ('report.txt', open('report.txt', 'rb'), 'text/plain')
}
response = requests.post(url, data=data, files=files) # files参数自动处理multipart
print(response.json())
# 方法二:使用poster模块(Python 2遗留方案,Python 3需适配)
# 注:poster模块可能不支持Python 3,此处仅作参考
# from poster.encode import multipart_encode
# from poster.streaminghttp import register_openers
# register_openers()
# datagen, headers = multipart_encode(data)
# req = urllib2.Request(url, datagen, headers)3. application/json
特点:数据为JSON字符串,需设置Content-Type: application/json。
import json
import requests
url = "http://httpbin.org/post"
data = {"package": "com.tencent.lian", "version_code": "66"}
# 使用requests(自动设置Content-Type为application/json)
response = requests.post(url, json=data) # 使用json参数
print(response.json())
# 使用urllib(手动编码)
json_data = json.dumps(data).encode('utf-8')
req = urllib.request.Request(url, data=json_data, method='POST')
req.add_header('Content-Type', 'application/json')
with urllib.request.urlopen(req) as resp:
print(resp.read().decode('utf-8'))4. text/xml
特点:数据为XML格式,需手动构建XML字符串并设置正确Content-Type。
import requests
url = "http://httpbin.org/post"
# 构建XML数据
xml_data = """<?xml version="1.0" encoding="utf-8"?>
<request>
<package>com.tencent.lian</package>
<version_code>66</version_code>
</request>"""
headers = {'Content-Type': 'application/xml'} # 或text/xml
response = requests.post(url, data=xml_data.encode('utf-8'), headers=headers)
print(response.text)四、总结与对比
| 编码类型 | 适用场景 | Python实现关键点 |
|---|---|---|
| x-www-form-urlencoded | 简单表单提交 | urllib.parse.urlencode 或 requests.post(data=dict) |
| multipart/form-data | 文件上传/混合表单 | requests.post(files=dict) 自动处理 |
| application/json | API交互(最常用) | requests.post(json=dict) 或手动 json.dumps |
| text/xml | 旧系统/XML-RPC | 手动构建XML字符串,设置headers |
建议:在现代Python开发中,优先使用requests库,它简化了不同POST格式的处理。若需兼容Python 2或旧项目,可参考参考资料中的urllib2实现。
注意:文中示例使用http://httpbin.org/post作为测试端点,这是一个开源的HTTP测试服务,会返回请求的详细信息,便于调试。实际开发中请替换为目标API地址。
到此这篇关于python实现http post四种请求体详解的文章就介绍到这了,更多相关python http post四种请求体内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
