2011-03-08 40 views
1

我正在嘗試使用httpwebrequest對象登錄到www.diary.com。但是,它總是無法登錄,並不斷給我回登錄頁面。任何人都可以啓發我什麼是錯誤的?c#httpwebrequest憑證問題

我的代碼如下:

// prepare the web page we will be asking for 
HttpWebRequest request = (HttpWebRequest) 
    WebRequest.Create(@"http://diary.com/events/agenda"); 

request.ContentType = "text/html"; 

request.Credentials = new NetworkCredential(@"[email protected]", "password"); 

request.AllowAutoRedirect = true; 
request.Referer = @"http://diary.com/"; 

// execute the request 
HttpWebResponse response = (HttpWebResponse) 
    request.GetResponse(); 

// we will read data via the response stream 
Stream resStream = response.GetResponseStream(); 

// set the WebBrowser object documentStream to the response stream 
myWB.DocumentStream = resStream; 

// simply tell me the title of the webpage 
MessageBox.Show(myWB.Document.Title); 

回答

5

您這裏有兩個問題:

  1. 您在協議層面,這是不提供憑證如何大多數網站(包括本文)工作。該協議是完全匿名的,並且該站點使用表單身份驗證來登錄。您的代碼需要實際創建一個模仿提交登錄表單的POST請求。從服務器返回的響應將包括一個包含驗證令牌的cookie,該驗證令牌將導入...

  2. 您需要跨請求保留cookie。在您提交登錄請求並獲取cookie之後,您需要掛起並將其發送到每個後續請求的請求標頭中。最簡單的方法是使用WebClient跨越多個請求,並使用CookieContainer來爲您跟蹤cookie。

如果您不確定如何模仿,你的瀏覽器和網站之間的流量了,用一個偉大的工具是Fiddler。它捕捉原始請求/響應,供您觀察。