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

 更新时间:2026年05月09日 09:48:48   作者:Chief395  
文章提供了15个使用Python的requests库调用HTTP接口进行POST请求的示例,包括发送简单POST请求,JSON/XML格式请求,文件/二进制数据请求等操作,感兴趣的小伙伴可以了解下

以下是使用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请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python管理包路径之pycharm自动解决包路径注册

    python管理包路径之pycharm自动解决包路径注册

    这篇文章主要介绍了python本管理包路径之pycharm自动解决包路径注册,文章通过围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • pandas DataFrame rsub的实现示例

    pandas DataFrame rsub的实现示例

    本文主要介绍了pandas DataFrame rsub的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-04-04
  • Python利用WMI实现ping命令的例子

    Python利用WMI实现ping命令的例子

    今天小编就为大家分享一篇Python利用WMI实现ping命令的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-08-08
  • Python import自己的模块报错问题及解决

    Python import自己的模块报错问题及解决

    这篇文章主要介绍了Python import自己的模块报错问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • Python基础教程之Pandas数据分析库详解

    Python基础教程之Pandas数据分析库详解

    Pandas是一个基于 NumPy 的非常强大的开源数据处理库,它提供了高效、灵活和丰富的数据结构和数据分析工具,本文中,我们将学习如何使用Pandas来处理和分析数据,感兴趣的小伙伴跟着小编一起来看看吧
    2023-07-07
  • python可迭代类型遍历过程中数据改变会不会报错

    python可迭代类型遍历过程中数据改变会不会报错

    这篇文章主要介绍了python可迭代类型遍历过程中数据改变会不会报错问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • 如何使用Python+ChatGPT批量生成论文

    如何使用Python+ChatGPT批量生成论文

    这篇文章主要介绍了用Python+ChatGPT批量生成论文,我用python+GPT-3 API开发了一个工具,可以直接从arxiv地址生成论文概述,需要的朋友可以参考下
    2023-02-02
  • Python实现图片分割的多种方法总结

    Python实现图片分割的多种方法总结

    图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择
    2025-04-04
  • Python3.5面向对象编程图文与实例详解

    Python3.5面向对象编程图文与实例详解

    这篇文章主要介绍了Python3.5面向对象编程,结合图文与实例形式详细分析了Python面向对象编程相关的概念、类定义、实例化、实例变量、类变量、析构函数等相关原理及使用技巧,需要的朋友可以参考下
    2019-04-04
  • python-docx如何缩进两个字符

    python-docx如何缩进两个字符

    笔者遇到这样的需求要求正文内容每段首行顶两格,也就是向右缩进两个字符,怎么操作呢?下面小编给大家带来了python-docx的缩进问题——如何缩进两个字符,需要的朋友可以参考下
    2022-11-11

最新评论