为什么要使用 ssl 认证请求 returns html?

Why request with ssl certification returns html?

我有一个问题

我正在尝试 post 向网络服务器发送一些数据并获得响应。 Webserver 有 SSL 证书验证,所以我为它提供了文件。在响应中我应该收到 xml 文件,但我收到一些 html.

我的小脚本是这样的:

import requests, sys, os

program_directory=sys.path[0]
verify = os.path.join(program_directory, "test.pem")
data='some data'

print requests.post('https://somewebsite', data=data, verify=verify).text

这是我之前得到的 html:

C:\Python27\lib\site-packages\requests\packages\urllib3\connection.py:251: SecurityWarning: Certificate has no `subjectAltName`, falling back to check for a `commonName` for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 for details.) SecurityWarning

如果我使用 verify=False 并且不提供文件,它工作正常并且 returns 正确的数据。可能是什么问题,为什么我会收到此警告和 html?

Apparently 如果您使用的是 Python2 2.7.2 或更低版本,则会生成此错误警告。

要忽略该警告,您可以使用 link 中的以下内容:

import requests
import warnings
with warnings.catch_warning():
    warnings.simplefilter('ignore')
    requests.post(...)

您的自签名证书不包含 subjectAltName

使用:

openssl req -new -x509 -key myselfsigned.key -out myselfsigned.cer -days 365 -subj /CN=www.mysite.com

生成证书。

引用 GrahamDumpleton:

This is because in older Python versions the _ssl module does not return 'subjectAltName' in the set of fields in the SSL certificate. That the field isn't returned even if present means that even if the SSL certificate is valid, the check will fail and the warning logged.

To eliminate the warnings you can disable urllib3 warnings globally.

requests 模块包含 urllib3 的捆绑版本,您很可能需要使用:

import requests
requests.packages.urllib3.disable_warnings()

如果您只想忽略该特定警告,您可以使用:

from requests.packages.urllib3.exceptions import SubjectAltNameWarning
requests.packages.urllib3.disable_warnings(SubjectAltNameWarning)