通过http发送基本身份验证

5

我正在尝试读取一个需要基本身份验证的页面的源代码。然而,即使在我的HttpWebRequest中使用标题和凭据,我仍然收到一个未经授权的异常[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身份验证结果

未出现Proxy-Authenticate标头。
出现了WWW-Authenticate标头:基本领域="示例"


我不知道你目前使用的是哪个版本的.NET,但我建议你开始使用HttpClient ;) - Matías Fidemraizer
将请求的授权头与不返回401的请求的授权头进行比较。 - CodeCaster
@CodeCaster:我会安装 Fiddler 并发布结果。 - Nick Prozee
我发布了 Fiddler 结果,两种情况下都应该有 n 个头。 - Nick Prozee
1个回答

4

消息提示:

没有 Proxy-Authenticate 头。

解决方法:

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

我希望你能够受益。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接