使用个人数字证书通过urllib2打开网址

0 投票
3 回答
1566 浏览
提问于 2025-04-16 15:22

我正在尝试使用urllib2来打开一个网页,这个网页需要用到个人数字证书。

其实通过命令行,用“curl -k”是可以打开这个资源的。

所以我想问的是:

1) 有没有可能在不使用个人数字证书的情况下,用urllib2打开这个网页?

2) 如果第一种方法不行,那我该怎么用urllib2和“个人数字证书”来访问这个资源呢?

附注:我正在尝试用以下代码来访问这个资源:


class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
    def init(self, key, cert):
        urllib2.HTTPSHandler.init(self)
        self.key = key
        self.cert = cert

def https_open(self, req):
    return self.do_open(self.getConnection, req)

def getConnection(self, host, timeout=300):
    return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)

opener = urllib2.build_opener(HTTPSClientAuthHandler('/Users/antonio/.globus/userkey.pem','/Users/antonio/.globus/usercert.pem') ) response = opener.open("https://........") print response.read()

我遇到的错误是:


Traceback (most recent call last):
  File "HTTPSClientAuthHandler.py", line 18, in 
    response = opener.open("https://cmsweb.cern.ch/tier0/express_config")
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 389, in open
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 502, in http_response
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 427, in error
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 361, in _call_chain
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 510, in http_error_default
urllib2.HTTPError: HTTP Error 500: Internal Server Error

3 个回答

0

你所做的工作对我来说基本上是没问题的,只有一个例外。初始化函数的名字前后必须有两个下划线,因为这是一个特殊的函数,用来初始化类。这个函数在每个类里都是一样的:

class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def _init_(self, key, cert):
urllib2.HTTPSHandler._init_(self)
self.key = key
self.cert = cert

0

我对pycurl不太熟悉,不过这里有一些链接可能对你有帮助:

使用PyCurl发送HTTP GET请求时遇到的问题(特别注意建议使用--libcurl example.c来获取libcurl的实现)

http://code.google.com/p/friendlycurl/

http://www.phpfreaks.com/forums/index.php?topic=270222.0

1

最后我解决了这个问题。

我通过不使用个人数字证书的方式,成功访问了https服务,具体方法如下:

txdata = None
txheaders = {
    'Accept': 'text/html'
}
req = urllib2.Request(url, txdata, txheaders)

有没有人知道为什么在请求头中加上 'Accept': 'text/html' 就能让我们连接到没有证书的SSL网站呢?

这可能和服务器的设置有关。

撰写回答