Python使用urllib.request调用HTTPS API时遭遇SSL协议错误求助
解决urllib.request调用GitHub API时的SSL协议错误
针对你遇到的<urlopen error EOF occurred in violation of protocol (_ssl.c:1091)>错误,以下是几个结合Azure DevOps流水线环境特性的针对性修复方案:
1. 改用显式代理处理器(替代环境变量方式)
直接设置HTTP_PROXY/HTTPS_PROXY环境变量在部分流水线环境中可能无法被urllib正确识别,显式配置代理处理器更可靠:
import urllib.request import ssl import json import os try: # 显式配置代理 proxy_handler = urllib.request.ProxyHandler({ 'http': '<redacted>', 'https': '<redacted>' }) opener = urllib.request.build_opener(proxy_handler) urllib.request.install_opener(opener) req = urllib.request.Request(f'https://api.github.com/repos/{repository_name}/languages') req.add_header('Accept', 'application/vnd.github+json') req.add_header('Authorization', f'Bearer {github_token}') # 先验证证书文件是否存在 if not os.path.exists(cert_path): print(f"证书文件不存在: {cert_path}") raise FileNotFoundError(f"缺失证书: {cert_path}") ssl_context = ssl.create_default_context(cafile=cert_path) # 强制禁用TLS 1.0/1.1,适配GitHub API的TLS版本要求 ssl_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 with urllib.request.urlopen(req, context=ssl_context) as response: gt_response = json.load(response) except ssl.SSLError as e: print(f'SSL协议错误: [{e}]') except urllib.error.URLError as e: print(f'URL请求错误: [{e}]') except Exception as e: print(f'其他错误: [{e}]')
2. 检查代理与SSL证书兼容性
- 如果使用HTTPS代理,确保代理的SSL证书已包含在
cert_path指定的证书链中;若仅用于测试,可临时调整上下文跳过代理证书验证(生产环境不建议):ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE - 确认Azure DevOps流水线中
cert_path的路径正确,可使用预定义变量(如$(Agent.TempDirectory)/certs.pem)定位证书文件。
3. 强制适配GitHub的TLS版本要求
GitHub API仅支持TLS 1.2及以上版本,通过ssl_context.options禁用旧版本TLS是核心修复点,避免因环境默认TLS版本过低导致握手失败。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

