Python 使用requests调用微信接口
1、使用requests执行GET和POST请求
1)GET请求
import requests
# 目标URL
url = 'http://example.com/api'
# 可选的参数字典
params = {
'key1': 'value1',
'key2': 'value2'
}
# 发起GET请求
response = requests.get(url, params=params)
# 检查响应状态码
if response.status_code == 200:
# 处理响应内容,例如解析JSON
data = response.json()
print(data)
else:
print('GET请求失败,状态码:', response.status_code)
2)POST请求
import requests
# 目标URL
url = 'http://example.com/api'
# 要发送的数据
data = {
'key1': 'value1',
'key2': 'value2'
}
# 发起POST请求
response = requests.post(url, data=data)
# 检查响应状态码
if response.status_code == 200:
# 处理响应内容
data = response.json()
print(data)
else:
print('POST请求失败,状态码:', response.status_code)
3)json参数和上传文件
json参数会使用json模块中的dumps方法转成json字符串,会请求头中的Content-Type:application/json,
import requests
# 目标URL
url = 'http://example.com/api'
# 发送JSON数据
response = requests.post(url, json=data) # `json=data`会自动将字典序列化为JSON字符串
# 上传文件
files = {'file': open('report.xls', 'rb')}
response = requests.post(url, files=files)
注意:json参数不需要提前使用json模块的方法转成json字符串。
2、调用微信接口
调用微信公众号或小程序接口时,需要注意POST请求传入数据编码问题,请求头中是否添加Content-Type:application/json。
1)GET请求
参考文档:
2)POST请求
参考文档:
注意:Python 中使用的 requeset 版本,可能同样的代码在不同版本出现不同的结果。
浙公网安备 33010602011771号