本文介绍了通过http发送基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从需要基本身份验证的页面中读取源代码。但是,在我的HttpWebRequest中使用Header甚至凭证,我仍然会收到未经授权的异常[401]。

I am trying to read the source from a page that requires basic authentication. However, using a Header and even Credentials in my HttpWebRequest, I still get a Unauthorized Exception [401] returned.

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 Auth Results


推荐答案

正如消息所说:

然后,解决方法:

...
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());
        }
    }
}
...

我希望它有所帮助。

这篇关于通过http发送基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 08:05