gpt4 book ai didi

c# - 通过 http 发送基本身份验证

转载 作者:太空狗 更新时间:2023-10-29 23:21:59 26 4
gpt4 key购买 nike

我正在尝试从需要基本身份验证的页面中读取源代码。但是,在我的 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());
}
}
}
...

希望对你有帮助。

关于c# - 通过 http 发送基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com