Skip to content

Instantly share code, notes, and snippets.

@nileshk
Created March 25, 2013 15:59
Show Gist options
  • Save nileshk/5238189 to your computer and use it in GitHub Desktop.
Save nileshk/5238189 to your computer and use it in GitHub Desktop.
Fetch contents of a URL with HTTP Basic Authentication
import urllib2
import base64
def fetch(url, username, password):
try:
request = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
return urllib2.urlopen(request).read()
except urllib2.HTTPError as ex:
print "Error connecting: " + str(ex)
except urllib2.URLError as ex:
print "Error connecting: " + str(ex)
return ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment