通过 http 发送基本身份验证

Sending Basic authentication over http

我正在尝试从需要基本身份验证的页面读取源代码。但是,在我的 HttpWebRequest 中使用 Header 甚至 Credentials,我仍然会返回 Unauthorized Exception [401]。

string urlAddress = URL;
string UserName = "MyUser";
string Password = "MyPassword";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);    
            if (UserName != string.Empty)
            {
                string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(UserName + ":" + Password));
                request.Headers.Add("Authorization", "Basic " + encoded);
                System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
                credentialCache.Add(
                    new System.Uri(urlAddress), "Basic", new System.Net.NetworkCredential(UserName, Password)
                );

                request.Credentials = credentialCache;

            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //<== Throws Exception 401

Fiddler 验证结果

No Proxy-Authenticate Header is present.
WWW-Authenticate Header is present: Basic realm="example"

正如消息所说:

No Proxy-Authenticate Header is present.

然后,解决方法:

...
string urlAddress = "http://www.google.com";
string userName = "user01";
string password = "puser01";
string proxyServer = "127.0.0.1";
int proxyPort = 8081;

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(urlAddress);

if (userName != string.Empty)
{
    request.Proxy = new WebProxy(proxyServer, proxyPort)
    {
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(userName, password)
    };

    string basicAuthBase64 = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", userName, password)));
    request.Headers.Add("Proxy-Authorization", string.Format("Basic {0}", basicAuthBase64));
}

using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
    var stream = response.GetResponseStream();
    if (stream != null)
    {
        //--print the stream content to Console
        using (var reader = new StreamReader(stream))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}
...

希望对您有所帮助。