2011-03-05 58 views
5

我試圖登錄到使用我的web應用程序的HttpWebRequest但我不斷收到以下錯誤:401未授權返回的GET請求(HTTPS)與正確的憑據

System.Net.WebException: The remote server returned an error: (401) Unauthorized. 

提琴手具有以下的輸出:

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

回答

9

試試這個:

 Uri uri = new Uri("https://mysite.com/auth"); 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri) as HttpWebRequest; 
     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. 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

的使用注意事項NetworkCredential類,而不是滾動自己的身份驗證標頭。

+2

這就是我第一次嘗試的方式,而我仍然得到401個。唯一的區別是Fiddler說請求中沒有授權標頭。 – David 2011-03-06 00:19:16

+0

您確定您使用的用戶名和密碼與您在Mac應用程序中使用的憑據相同嗎? – 2011-03-06 06:36:11

+0

是的,我絕對相信。是否有另一個類似webrequest的圖書館我可以試試? – David 2011-03-06 08:47:06

相關問題