requests.get发送https请求报错,两种情况解决方法


发送https请求

代码如下,用python的requests发送https请求,下载文件

down_url = 'https://ip:port'  # https 地址
requests.get(down_url)  # 发送https请求

遇到问题一:

控制台返回报错如下:

  • Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1091)'))

从提示SSLCertVerificationError可以看出证书认证错误

解决方法1:

requests.get(down_url, verify=False)  # 发送https请求时,加入verify=False,忽略证书验证

解决方法2:

给服务器上传正式证书。条件有限的情况下,不做考虑,所以不推荐该方法

遇到问题二:

问题一通过verify=False搞定后,又报错如下,提示不安全认证

  • C:\Python37\lib\site-packages\urllib3\connectionpool.py:986: InsecureRequestWarning: Unverified HTTPS request is being made to host 'IP地址'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning,

解决方法:

# 来自官方文档
import urllib3
urllib3.disable_warnings()  # 将这段代码放到调用https的代码段中,避免其他模块调用时仍报该错

打开连接,官方文档给出了解决方案

# 以下内容摘自官方文档
TLS Warnings
urllib3 will issue several different warnings based on the level of certificate verification support. These warnings indicate particular situations and can be resolved in different ways.

InsecureRequestWarning
This happens when a request is made to an HTTPS URL without certificate verification enabled. Follow the certificate verification guide to resolve this warning.

Making unverified HTTPS requests is strongly discouraged, however, if you understand the risks and wish to disable these warnings, you can use disable_warnings():

import urllib3

urllib3.disable_warnings()
Alternatively you can capture the warnings with the standard logging module:

logging.captureWarnings(True)

你可能感兴趣的:(接口测试,requests,HTTPS,TLS,ssl)