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("http://127.0.0.1:8000/custom/get/")
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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s