NetworkCredential 401未经授权的HttpWebRequest

时间:2015-10-26 14:31:11

标签: c# httpwebrequest http-status-code-401 www-authenticate

我在验证HttpWebRequest

时遇到问题
  

远程服务器返回错误:(401)未经授权。

这是我的代码:

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);

但这也没有帮助。

1 个答案:

答案 0 :(得分:0)

如果您在公司网络上,则可能是代理服务器呈现401而不是您期望的最终Web服务器。记住这一点。

尝试将授权从基本设置为NTLM

如果没有关于您要连接的应用程序的大量信息,并且网络配置只是猜测工作