Python3.9+版本requests调用SOAP API报错问题求助
问题排查与解决方案
问题描述
调用自签名证书的SOAP API服务(地址:https://ws.hph.hu:10446/v1b/OrderInfos.svc)时出现Python版本兼容问题:
- Python 3.9环境:仅在添加
verify=False参数时能正常运行;移除该参数会触发SSL验证失败错误:Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - Python 3.10及以上环境:无论是否保留
verify=False,均报错:[Errno 10054] An existing connection was forcibly closed by the remote host.
可能的原因与解决办法
1. 适配SSL/TLS协议版本
Python 3.10+默认的TLS协议版本可能高于服务器支持的版本,导致握手失败被远程关闭。可以指定兼容的协议版本:
import requests from requests.adapters import HTTPAdapter from urllib3.poolmanager import PoolManager import ssl class TLSAdapter(HTTPAdapter): def init_poolmanager(self, *args, **kwargs): ctx = ssl.create_default_context() # 降低安全级别并禁用高版本TLS,适配服务器配置 ctx.set_ciphers('DEFAULT@SECLEVEL=1') ctx.options |= ssl.OP_NO_TLSv1_3 kwargs['ssl_context'] = ctx return super().init_poolmanager(*args, **kwargs) url="https://ws.hph.hu:10446/v1b/OrderInfos.svc" message="""soap xml""" s = requests.Session() # 挂载自定义适配器 s.mount('https://', TLSAdapter()) s.headers = {} headers={"Content-Type":"text/xml; charset=utf-8", "SOAPAction":"soap-action", "Expect":"100-continue", "Connection":"Keep-Alive"} r=s.post(url,data=message,headers=headers,verify=False)
2. 导入自签名证书(安全方案)
跳过证书验证存在安全风险,建议将服务器的自签名证书加入信任链:
- 从Firefox导出该网站的自签名证书(保存为PEM格式)
- 在请求中指定证书路径:
# 替换为你的证书实际路径 r=s.post(url,data=message,headers=headers,verify='/path/to/your/cert.pem')
也可以将证书添加到Python的系统信任证书目录(Linux通常是/etc/ssl/certs,Windows为Python安装目录下的Lib\site-packages\certifi\cacert.pem)
3. 移除Expect: 100-continue头部
部分服务器在Python 3.10+环境下对100-continue头部的处理存在兼容问题,尝试移除该头部:
headers={"Content-Type":"text/xml; charset=utf-8", "SOAPAction":"soap-action", "Connection":"Keep-Alive"} # 去掉Expect头部后重新发起请求
内容的提问来源于stack exchange,提问作者KJG
相关产品推荐
相关产品推荐

