Python 3下执行带鉴权头的curl命令并获取接口响应的实现方法
等效Python3网络请求实现
推荐方案:使用requests库(开发效率最高)
首先安装依赖:
pip install requests
实现代码:
import requests # 替换为实际目标地址(原curl的换行转义反斜杠已自动拼接为完整URL) target_url = "https://api.abc.com/targets/targetID" # 替换为真实的JWT鉴权值 auth_token = "PROBELY_AUTH_TOKEN" # 完全对应原curl的请求头配置 headers = { "Content-Type": "application/json", "Authorization": f"JWT {auth_token}" } # 原curl未携带请求体,因此无需传入data/json参数 response = requests.post(target_url, headers=headers) # 按需获取响应内容 print("接口返回状态码:", response.status_code) # 纯文本格式响应 resp_text = response.text # JSON格式响应(接口返回JSON时可直接解析为字典) resp_json = response.json()
注意:如果请求时出现SSL证书验证失败的报错,且为可信内网接口,可在
requests.post中追加verify=False参数跳过校验;公网生产环境不建议关闭该校验。
如果原curl实际附带了未粘贴的POST请求体(如存在-d '{"field": "value"}'参数),只需在requests.post中追加json=你的请求体字典即可,requests会自动处理序列化与请求头匹配。
无第三方依赖方案:使用Python内置urllib库
无需安装任何额外包,直接运行:
import urllib.request import json target_url = "https://api.abc.com/targets/targetID" auth_token = "PROBELY_AUTH_TOKEN" headers = { "Content-Type": "application/json", "Authorization": f"JWT {auth_token}" } # 构造POST请求,无请求体时data传入None req = urllib.request.Request(target_url, data=None, headers=headers, method="POST") # 发送并获取响应 with urllib.request.urlopen(req) as resp: print("接口返回状态码:", resp.status) # 解码纯文本响应 resp_text = resp.read().decode("utf-8") # 解析JSON格式响应 resp_json = json.loads(resp_text)
内容的提问来源于stack exchange,提问作者Johnst33
相关产品推荐
相关产品推荐

