2011-09-29 35 views
1

我需要登錄到一個網站,從各種頁面登錄時下載源代碼。我能夠做到這一點很容易,當使用Windows窗體WebBrowser類,但這不是合適的,我需要能夠通過WebRequest或其他人做到這一點。不幸的是,它不喜歡我如何處理cookie。C#登錄網站和使用WebRequest下載源代碼 - 問題與Cookie

我使用以下代碼並獲得以下響應:{「w_id」:「LoginForm2_6」,「message」:「請在您的瀏覽器中啓用cookie以便登錄。」,「success」:0, 「showLink」:false}

string url2 = "%2Fapp%2Futils%2Flogin_form%2Fredirect%2Fhome"; 
string login = "username"; 
string password = "password"; 
string w_id = "LoginForm2_6"; 
string loginurl = "http://loginurl.com"; 

string cookieHeader; 

WebRequest req = WebRequest.Create(loginurl); 
req.Proxy = WebRequest.DefaultWebProxy; 
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 
req.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 
req.Method = "POST"; 
string postData = string.Format("w_id={2}&login={0}&password={1}&url2={3}", login, password, w_id, url2); 
byte[] bytes = Encoding.ASCII.GetBytes(postData); 
req.ContentLength = bytes.Length; 
using (Stream os = req.GetRequestStream()) 
{ 
os.Write(bytes, 0, bytes.Length); 
} 
WebResponse resp = req.GetResponse(); 
cookieHeader = resp.Headers["Set-cookie"]; 

string pageSource = ""; 
using (StreamReader sr = new StreamReader(resp.GetResponseStream())) 
{ 
pageSource = sr.ReadToEnd(); 
} 
richTextBox1.Text = pageSource; 

如果有人可以告訴我我哪裏出錯了,那將不勝感激。

此外,爲了讓你知道,如果我用web瀏覽器類下面,它工作在精細:

b.Navigate(fullurl, "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n"); 

回答

0

我知道這是舊的回覆,但用戶Matthew Brindley回答類似question用完全可行的例子。問題是關於訪問需要用戶以前登錄的網站的 源代碼。全部使用C#應用程序完成,使用WebRequestWebResponse