python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python发送HTTP请求

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

作者: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格式:

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

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