import requests
# 定义请求的URL和参数
url = 'https://example.com/api' # 替换为实际的API地址
data = {
'key1': 'value1',
'key2': 'value2'
}
# 发送POST请求
response = requests.post(url, data=data)
# 检查响应状态码
if response.status_code == 200:
print('请求成功')
# 打印返回的内容
print(response.text)
else:
print(f'请求失败,状态码: {response.status_code}')
# 如果需要发送JSON数据,可以使用json参数
json_data = {
'key1': 'value1',
'key2': 'value2'
}
response = requests.post(url, json=json_data)
# 如果需要添加请求头
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
}
response = requests.post(url, json=json_data, headers=headers)
requests
是一个常用的HTTP请求库,用于发送各种HTTP请求。url
是目标API的地址,data
是要发送的数据(表单格式),json_data
是要发送的JSON格式数据。requests.post()
方法发送POST请求。可以通过 data
参数发送表单数据,通过 json
参数发送JSON数据。response.status_code
检查服务器返回的状态码,200表示请求成功。response.text
获取响应的内容,可以是文本、JSON等格式。headers
参数添加自定义的请求头,例如设置 Content-Type
或者认证信息。上一篇:python 随机函数
下一篇:python导入文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站