All posts by ykyuen

Life is for fun~ =)

Python – Open URL with HTTP Authentication using urllib2

We could add HTTP authentication credential when opening and URL using urllib2.

import urllib2
import base64
import simplejson

username = "<username>"
password = "<password>"
request = urllib2.Request("")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)

data = simplejson.load(response)
print data


Done =)

Reference: StackOverflow – Python urllib2 Basic Auth Problem