Python urllib2, basic HTTP authentication, and tr.im Python urllib2, basic HTTP authentication, and tr.im python python

Python urllib2, basic HTTP authentication, and tr.im


This seems to work really well (taken from another thread)

import urllib2, base64request = urllib2.Request("http://api.foursquare.com/v1/user")base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')request.add_header("Authorization", "Basic %s" % base64string)   result = urllib2.urlopen(request)


Really cheap solution:

urllib.urlopen('http://user:xxxx@api.tr.im/api')

(which you may decide is not suitable for a number of reasons, like security of the url)

Github API example:

>>> import urllib, json>>> result = urllib.urlopen('https://personal-access-token:x-oauth-basic@api.github.com/repos/:owner/:repo')>>> r = json.load(result.fp)>>> result.close()


Take a look at this SO post answer and also look at this basic authentication tutorial from the urllib2 missing manual.

In order for urllib2 basic authentication to work, the http response must contain HTTP code 401 Unauthorized and a key "WWW-Authenticate" with the value "Basic" otherwise, Python won't send your login info, and you will need to either use Requests, or urllib.urlopen(url) with your login in the url, or add a the header like in @Flowpoke's answer.

You can view your error by putting your urlopen in a try block:

try:    urllib2.urlopen(urllib2.Request(url))except urllib2.HTTPError, e:    print e.headers    print e.headers.has_key('WWW-Authenticate')