Fetching a Page with Basic Authentication

Adapted from this blog entry.

Uses the NetworkCredential class to set a username and password, for a URL that requires basic authentication. It also sets a UserAgent on the request and investigates the headers of the response: from System.IO import StreamReader from System.Net import HttpWebRequest, NetworkCredential

req = HttpWebRequest.Create("http://www.example.com/") req.Method = "GET" req.Credentials = NetworkCredential("username", "password")

req.UserAgent = "IronPython"

rsp = req.GetResponse try: print "============ begin headers ==================" for h in rsp.Headers: print h + ": " + rsp.Headers[h] print "============ end headers ==================" print "============ begin response ==================" print "" print StreamReader(rsp.GetResponseStream).ReadToEnd print "" print "============ end of response ==================" finally: print "closing response" rsp.Close

Back to Contents.