我正在尝试使用HttpWebRequest登录我的网络应用,但我不断收到以下错误:
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
Fiddler有以下输出:
Result Protocol Host URL
200 HTTP CONNECT mysite.com:443
302 HTTPS mysite.com /auth
401 HTTP mysite.com /auth
这就是我正在做的事情:
// to ignore SSL certificate errors
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
try
{
// request
Uri uri = new Uri("https://mysite.com/auth");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri) as HttpWebRequest;
request.Accept = "application/xml";
// authentication
string user = "user";
string pwd = "secret";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
request.Headers.Add("Authorization", auth);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
// response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
// Cleanup
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException webEx)
{
Console.Write(webEx.ToString());
}
我可以在Mac应用中使用ASIHTTPRequest登录到同一个站点,没有问题:
NSURL *login_url = [NSURL URLWithString:@"https://mysite.com/auth"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:login_url];
[request setDelegate:self];
[request setUsername:name];
[request setPassword:pwd];
[request setRequestMethod:@"GET"];
[request addRequestHeader:@"Accept" value:@"application/xml"];
[request startAsynchronous];
答案 0 :(得分:9)
试试这个:
var uri = new Uri("https:/example.com/auth");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Accept = "application/xml";
// authentication
var cache = new CredentialCache();
cache.Add(uri, "Basic", new NetworkCredential("user", "secret"));
request.Credentials = cache;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
// response.
var response = (HttpWebResponse)request.GetResponse();
请注意使用NetworkCredential
类,而不是滚动自己的身份验证标头。