当前位置: 代码网 > it编程>前端脚本>Python > Python使用POST方法发送HTTP请求的15个示例代码

Python使用POST方法发送HTTP请求的15个示例代码

2026年05月09日 Python 我要评论
以下是使用requests库调用http接口进行post请求的15个示例:1.发送简单的post请求:import requestspayload = {'key1': 'value1', 'key2

以下是使用requests库调用http接口进行post请求的15个示例:

1.发送简单的post请求:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://example.com', data=payload)
print(response.text)

2.发送json格式的post请求:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://example.com', json=json.dumps(payload))
print(response.text)

3.发送xml格式的post请求:

import requests

payload = '<xml><key1>value1</key1><key2>value2</key2></xml>'
response = requests.post('http://example.com', data=payload, headers={'content-type': 'application/xml'})
print(response.text)

4.发送文件的post请求:

import requests

files = {'file': open('file.txt', 'rb')}
response = requests.post('http://example.com', files=files)
print(response.text)

5.发送二进制数据的post请求:

import requests

data = b'\x00\xff\x00\xff'
response = requests.post('http://example.com', data=data, headers={'content-type': 'application/octet-stream'})
print(response.text)

6.发送多个文件的post请求:

import requests

files = [('file1', open('file1.txt', 'rb')), ('file2', open('file2.txt', 'rb'))]
response = requests.post('http://example.com', files=files)
print(response.text)

7.发送表单的post请求:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://example.com', data=payload, headers={'content-type': 'application/x-www-form-urlencoded'})
print(response.text)

8.发送json格式的post请求并带认证信息:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
auth = ('user', 'password')
response = requests.post('http://example.com', json=json.dumps(payload), auth=auth)
print(response.text)

9.发送json格式的post请求并带headers:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'content-type': 'application/json'}
response = requests.post('http://example.com', json=json.dumps(payload), headers=headers)
print(response.text)

10.发送json格式的post请求并带cookies:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
cookies = {'name': 'value'}
response = requests.post('http://example.com', json=json.dumps(payload), cookies=cookies)
print(response.text)

11.发送json格式的post请求并设置超时时间:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
timeout = 10
response = requests.post('http://example.com', json=json.dumps(payload), timeout=timeout)
print(response.text)

12.发送json格式的post请求并设置代理:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
proxies = {'http': 'http://proxy.example.com:8080'}
response = requests.post('http://example.com', json=json.dumps(payload), proxies=proxies)
print(response.text)

13.发送json格式的post请求并设置ssl认证:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://example.com', json=json.dumps(payload), verify=true)
print(response.text)

14.发送json格式的post请求并禁用ssl认证:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://example.com', json=json.dumps(payload), verify=false)
print(response.text)

15.发送json格式的post请求并设置ssl认证证书:

import requests
import json

payload = {'key1': 'value1', 'key2': 'value2'}
cert = ('client.crt', 'client.key')
response = requests.post('https://example.com', json=json.dumps(payload),cert=cert)
print(response.text)

知识扩展

python实现http post四种请求体

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

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

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

1.四种请求体格式简介

根据参考资料中的描述:

  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格式包裹。

2.环境准备

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

pip install requests

若使用传统方法,需注意python 3中urllib2已拆分为urllib.requesturllib.error

3.代码实现

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())

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)

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'))

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使用post方法发送http请求的15个示例代码的文章就介绍到这了,更多相关python发送http请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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