验证 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);
但这也无济于事。