Skip to content

Instantly share code, notes, and snippets.

@michaelhelmick
Created April 23, 2012 14:57
Show Gist options
  • Save michaelhelmick/2471457 to your computer and use it in GitHub Desktop.
Save michaelhelmick/2471457 to your computer and use it in GitHub Desktop.
Fix SSL Error in urllib
import httplib
import ssl
import socket
import sys
import urllib2
class HTTPSConnectionV3(httplib.HTTPSConnection):
def __init__(self, *args, **kwargs):
httplib.HTTPSConnection.__init__(self, *args, **kwargs)
def connect(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if sys.version_info < (2, 6, 7):
if hasattr(self, '_tunnel_host'):
self.sock = sock
self._tunnel()
else:
if self._tunnel_host:
self.sock = sock
self._tunnel()
try:
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv3)
except ssl.SSLError:
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
class HTTPSHandlerV3(urllib2.HTTPSHandler):
def https_open(self, req):
return self.do_open(HTTPSConnectionV3, req)
urllib2.install_opener(urllib2.build_opener(HTTPSHandlerV3()))
urllib2.urlopen("https://yoursecureurl.com/")
@klacha
Copy link

klacha commented Dec 18, 2013

great, fixes my problem, thanks!

@tclh123
Copy link

tclh123 commented Aug 18, 2014

Does this shows that requests is better than urllib2 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment