Python Requests调用API获取Bearer Token遇SSL错误求助
解决Python Requests调用自签名证书API的SSL验证失败问题
问题原因
目标API使用自签名SSL证书,Requests库默认会严格验证证书有效性,因此抛出SSLCertVerificationError错误;Postman默认允许跳过自签名证书验证或已导入对应证书,所以能成功请求。
解决方案
方案1:临时禁用SSL验证(仅开发/测试环境)
在post请求中添加verify=False参数,跳过证书验证:
import requests from urllib3.exceptions import InsecureRequestWarning # 屏蔽不安全请求的警告(可选) requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) url = "https://322.286.24.01/ach/ach_api/login" payload = {'username': 'test', 'password': 'test12'} response = requests.post(url, data=payload, verify=False) print(response.text)
注意:此方法存在安全风险,禁止在生产环境使用。
方案2:导入自签名证书(生产环境推荐)
将目标API的自签名证书保存为.pem或.crt格式文件,在请求中指定证书路径:
import requests url = "https://322.286.24.01/ach/ach_api/login" payload = {'username': 'test', 'password': 'test12'} # 替换为你的自签名证书实际路径 cert_path = "/path/to/your/self-signed-cert.pem" response = requests.post(url, data=payload, verify=cert_path) print(response.text)
内容的提问来源于stack exchange,提问作者stacktesting
相关产品推荐
相关产品推荐

