gpt4 book ai didi

python - HTTPS 连接 Python

转载 作者:IT老高 更新时间:2023-10-28 21:34:00 28 4
gpt4 key购买 nike

我正在尝试验证该目标是否公开了 https 网络服务。我有通过 HTTP 连接的代码,但我不确定如何通过 HTTPS 连接。我读过你使用 SSL,但我也读过它不支持证书错误。我得到的代码来自 python 文档:

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason

有人知道如何连接到 HTTPS 吗?

我已经尝试过 HTTPSConenction,但它以错误代码响应,声称 httplib 没有属性 HTTPSConnection。我也没有可用的 socket.ssl。

我已经安装了 Python 2.6.4,但我认为它没有编译 SSL 支持。有没有办法将此支持集成到较新的 python 中而无需再次安装。

我已经安装了 OpenSSL 和 pyOpenSsl,并且我已经从一个答案中尝试了以下代码:

import urllib2
from OpenSSL import SSL
try:
response = urllib2.urlopen('https://example.com')
print 'response headers: "%s"' % response.info()
except IOError, e:
if hasattr(e, 'code'): # HTTPError
print 'http error code: ', e.code
elif hasattr(e, 'reason'): # URLError
print "can't connect, reason: ", e.reason
else:
raise

我有一个错误:

    Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 87, in urlopen
return opener.open(url)
File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 203, in open
return self.open_unknown(fullurl, data)
File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 215, in open_unknown
raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

有谁知道如何让它工作?

-- UPDATE

我发现了问题所在,我使用的 Python 版本不支持 SSL。我目前在以下位置找到了此解决方案:http://www.webtop.com.au/compiling-python-with-ssl-support .

代码现在可以在这个非常好的解决方案之后运行。当我导入 ssl 和 HTTPSConnection 时,我知道不会出错。

感谢大家的帮助。

最佳答案

Python 2.x:docs.python.org/2/library/httplib.html :

Note: HTTPS support is only available if the socket module was compiled with SSL support.

Python 3.x:docs.python.org/3/library/http.client.html :

Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).

#!/usr/bin/env python

import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# =>
# 200 OK
# <!DOCTYPE html ....

要验证是否启用了 SSL,请尝试:

>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>

关于python - HTTPS 连接 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146383/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com