A note that sends HTTP with a Basic authentication header in Python.
I use urllib2, but according to the manual, HTTPPasswordMgrWithDefaultRealm and HTTPBasicAuthHandler are deadly annoying.
In such a case, you can write the header yourself.
It's easy to talk about, just put the value Basic (base64 hash value of" username: password ")
in the header key ʻauthorization`.
When written in code
headers["authorization"] = "Basic " + (user + ":" + pass).encode("base64")[:-1]
OK. The last [: -1] has the line feed code removed.
The whole code looks like the following
import urllib2
url = "http://sample.com/index.html"
user = "XXXX"
password = "XXXX"
headers ={}
headers["authorization"] = "Basic " + (user + ":" + password).encode("base64")[:-1]
req = urllib2.Request(url=url, headers=headers)
res = urllib2.urlopen(req)
print(res.read())
It was really easy.
Recommended Posts