San*_* Hs 49 python urllib2 python-2.7 python-requests
我想certification validation在使用内部企业链接向服务器发出请求时忽略它.
使用python requests库我会这样做:
r = requests.get(link, allow_redirects=False,verify=False)
Run Code Online (Sandbox Code Playgroud)
如何使用urllib2库进行相同的操作?
Enn*_*per 128
在此期间,urllib2似乎默认验证服务器证书.过去显示 的警告消失了2.7.9,我目前在带有自签名证书(和Python 2.7.9)的测试环境中遇到了这个问题.
我的邪恶解决方法(不要在生产中这样做!):
import urllib2
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urllib2.urlopen("https://your-test-server.local", context=ctx)
Run Code Online (Sandbox Code Playgroud)
根据文档调用SSLContext构造函数也应该直接工作.我没试过.
Kro*_*ron 41
最简单的方法:
python 2
import urllib2, ssl
request = urllib2.Request('https://somedomain.co/')
response = urllib2.urlopen(request, context=ssl._create_unverified_context())
Run Code Online (Sandbox Code Playgroud)
蟒蛇3
from urllib.request import urlopen
import ssl
response = urlopen('https://somedomain.co', context=ssl._create_unverified_context())
Run Code Online (Sandbox Code Playgroud)
小智 33
对于那些使用开瓶器的人,你可以根据EnnoGröper的优秀答案达到同样的效果:
import urllib2, ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx), your_first_handler, your_second_handler[...])
opener.addheaders = [('Referer', 'http://example.org/blah.html')]
content = opener.open("https://localhost/").read()
Run Code Online (Sandbox Code Playgroud)
然后像以前一样使用它.
根据build_opener和HTTPSHandler,如果ssl模块存在,则添加HTTPSHandler ,这里我们只指定自己的而不是默认的.
小智 5
根据@EnnoGröper的帖子,我已经尝试了SSLContext构造函数,它在我的机器上运行良好。代码如下:
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)
Run Code Online (Sandbox Code Playgroud)
如果您需要开启器,只需添加以下上下文:
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))
Run Code Online (Sandbox Code Playgroud)
注意:以上所有测试环境均为python 2.7.12。我在这里使用PROTOCOL_SSLv23,因为文档如此说,其他协议也可能适用,但取决于您的计算机和远程服务器,请查看文档以获取详细信息。
| 归档时间: |
|
| 查看次数: |
106256 次 |
| 最近记录: |