Created
May 16, 2017 19:48
-
-
Save hmm01i/0b969b378e3b2455ff2ed7c2405f43bd to your computer and use it in GitHub Desktop.
Example of urllib with basic auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# just an example for me to remember | |
import urllib2, base64 | |
username = "testuser" | |
password = "changeme" | |
url = "https://example.com/" | |
request = urllib2.Request(url) | |
b64auth = base64.standard_b64encode("%s:%s" % (username,password)) | |
request.add_header("Authorization", "Basic %s" % b64auth) | |
result = urllib2.urlopen(request) | |
print(result.read()) |
good
Example for Python3 using the new urllib
.
from urllib import request
import base64
username = "testuser"
password = "changeme"
url = "https://example.com/"
b64auth = base64.standard_b64encode(('%s:%s' % (username, password)).encode()).decode()
headers = {
'Authorization': 'Basic %s' % b64auth
}
req = request.Request(url, headers=headers)
resp = request.urlopen(req)
print(resp.read().decode('utf-8'))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just wanted to say that this thing just saved my life. I spent HOURS searching for things on stackoverflow and python docs on how to do basic authentication using the standard libraries. Thank you. <3