当前位置: 代码网 > it编程>前端脚本>Python > python实现http post四种请求体详解

python实现http post四种请求体详解

2026年03月03日 Python 我要评论
在http协议中,post请求通常用于向服务器提交数据。虽然协议本身不强制规定数据的编码方式,但实际开发中形成了四种常见的content-type格式:application/x-www-form-u

在http协议中,post请求通常用于向服务器提交数据。虽然协议本身不强制规定数据的编码方式,但实际开发中形成了四种常见的content-type格式:

  • application/x-www-form-urlencoded(表单提交)
  • multipart/form-data(文件上传)
  • application/json(json数据)
  • text/xml(xml数据)

本文将结合python代码(同时涵盖传统urllib2和现代requests库),详细演示如何实现这四种请求体。

一、四种请求体格式简介

根据参考资料中的描述:

  1. application/x-www-form-urlencoded:浏览器原生表单默认格式,数据被编码为键值对(如key1=value1&key2=value2)。
  2. multipart/form-data:用于文件上传,数据被分为多个部分,每部分包含字段名和内容,由边界符(boundary)分隔。
  3. application/json:将数据结构序列化为json字符串,目前最流行的api数据交换格式。
  4. text/xml:基于xml的远程调用规范(如xml-rpc),数据以xml格式包裹。

二、环境准备

我们将使用python 3.x进行演示。如果使用现代开发,推荐安装第三方库requests(更简洁):

pip install requests

若使用传统方法,需注意python 3中urllib2已拆分为urllib.requesturllib.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.urlencoderequests.post(data=dict)
multipart/form-data文件上传/混合表单requests.post(files=dict) 自动处理
application/jsonapi交互(最常用)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四种请求体内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com