Python – Open URL with HTTP Authentication using urllib2

Update @ 2015-04-01: Mart suggests using the Requests package. =)

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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