import requests
# 定义请求的URL
url = 'https://api.example.com/data'
# 定义请求参数(如果需要)
params = {
'param1': 'value1',
'param2': 'value2'
}
# 发送GET请求
response = requests.get(url, params=params)
# 检查响应状态码
if response.status_code == 200:
# 如果请求成功,解析返回的JSON数据
data = response.json()
print("请求成功,返回的数据是:", data)
else:
print("请求失败,状态码:", response.status_code)
# 发送POST请求示例
payload = {
'key1': 'value1',
'key2': 'value2'
}
headers = {
'Content-Type': 'application/json'
}
response_post = requests.post(url, json=payload, headers=headers)
if response_post.status_code == 200:
data_post = response_post.json()
print("POST请求成功,返回的数据是:", data_post)
else:
print("POST请求失败,状态码:", response_post.status_code)
requests 是一个常用的Python库,用于发送HTTP请求。url 是API的地址,params 是GET请求中传递的查询参数。requests.get() 方法发送GET请求,并将响应存储在 response 变量中。response.status_code 检查请求是否成功(200表示成功)。response.json() 方法解析返回的JSON数据。requests.post() 方法发送POST请求,传递JSON格式的数据和请求头。以上代码展示了如何使用Python调用HTTP接口,包括GET和POST请求的基本用法。
上一篇:pythonrandom
下一篇:python,selenium
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站