NetworkCredential 401 unauthorized HttpWebRequest
本文关键字:HttpWebRequest unauthorized NetworkCredential | 更新日期: 2023-09-27 18:19:13
验证HttpWebRequest时出现问题
远程服务器返回错误:(401)Unauthorized.
这是我的代码:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
NetworkCredential networkCredential = new NetworkCredential(username, password);
WebRequest http = HttpWebRequest.Create(new Uri(url));
http.Timeout = timeout;
http.PreAuthenticate = true;
http.Credentials = networkCredential;
try
{
HttpWebResponse ws = (HttpWebResponse)http.GetResponse();
Stream str = ws.GetResponseStream();
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
和我尝试用另一种方式设置授权:
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
http.Headers.Add("Authorization", authorization);
如果您在公司网络上,它可能是呈现401的代理服务器,而不是您期望的终端web服务器。记住这一点。
尝试将授权从基本设置为NTLM
如果没有关于您正在连接的应用程序和网络配置的大量信息,那么它只是猜测工作