Python – Custom host mapping in urllib2

The urllib2 package allows us to override the host table before we make request. Here is an example which will map www.google.com to my local machine.

import urllib2
import httplib
import socket
import urllib2
import simplejson

def MyResolver(host):
  if host == 'www.google.com':
    return '127.0.0.1'
  else:
    return host

class MyHTTPConnection(httplib.HTTPConnection):
  def connect(self):
    self.sock = socket.create_connection((MyResolver(self.host),self.port),self.timeout)
class MyHTTPSConnection(httplib.HTTPSConnection):
  def connect(self):
    sock = socket.create_connection((MyResolver(self.host), self.port), self.timeout)
    self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)

class MyHTTPHandler(urllib2.HTTPHandler):
  def http_open(self,req):
    return self.do_open(MyHTTPConnection,req)

class MyHTTPSHandler(urllib2.HTTPSHandler):
  def https_open(self,req):
    return self.do_open(MyHTTPSConnection,req)

opener = urllib2.build_opener(MyHTTPHandler,MyHTTPSHandler)
urllib2.install_opener(opener)

response = urllib2.urlopen("http://www.google.com:8000/custom/get/")
data = simplejson.load(response)
print data

 

Done =)

Reference: StackOverflow – Tell urllib2 to use custom DNS

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.