HTTP GET request with basic authorization?

John Reese jtr at ofb.net
Mon Jan 3 19:30:29 EST 2005


On 03 Jan 2005 18:27:52 +0000, John J. Lee <jjl at pobox.com> wrote:
> Jonas Galvez <jonasgalvez at gmail.com> writes:
>
>> Christopher J.  wrote:
>> > I tried this, but it didn't work:
>> > conn.request("GET", "/somepage.html", None,
>> > {"AUTHORIZATION": "Basic username:password"})
> [...]
>> import re, base64, urllib2
>>  
>> userpass = ('user', 'pass')
>> url = 'http://somewhere'
>> 
>> request = urllib2.Request(url)
>> authstring = base64.encodestring('%s:%s' % userpass)
>> authstring = authstring.replace('\n', '')
>> request.add_header("Authorization", "Basic %s" % authstring)
>>  
>> content = urllib2.urlopen(request).read()
>
> There are handlers in urllib2 to do this for you, you shouldn't need
> to do it by hand.  I rarely do, so I won't risk an example...
>
>
> John
>

The way to do it with the handlers follows; oddly, it's just about as
long.

import urllib2

url = 'http://somewhere'
realm, user, pass = 'realm', 'user', 'pass'
hm = urllib2.HTTPPasswordMgrWithDefaultRealm()
hm.add_password(realm, url, user, pass)
od = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(hm))
content = od.open(url).read()



More information about the Python-list mailing list