在大家都不滿之前,這已被回答。我在網上搜尋瞭如何做到這一點,並嘗試了很多方法。 Login to website, via C#和How to programmatically log in to a website to screenscape?這兩個都很有幫助,但我無法弄清楚爲什麼我無法通過登錄頁面。這裏是我的代碼:使用C登錄網站#
string url = "https://www.advocare.com/login.aspx";
string url2 = "https://url.after.login";
HttpWebRequest wReq = WebRequest.Create(url) as HttpWebRequest;
wReq.KeepAlive = true;
wReq.Method = "POST";
wReq.AllowAutoRedirect = false;
wReq.ContentType = "application/x-www-form-urlencoded";
string postData = "ctl00$cphContent$txtUserName=Username&ctl00$cphContent$txtPassword=Password";
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
wReq.ContentLength = dataBytes.Length;
using (Stream postStream = wReq.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse;
string pageSource;
wReq = WebRequest.Create(url2) as HttpWebRequest;
wReq.CookieContainer = new CookieContainer();
wReq.CookieContainer.Add(wResp.Cookies);
HttpWebResponse wResp2 = wReq.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(wResp2.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
每當我看到pageSource它是login.aspx頁面的HTML。我必須在這裏錯過一些東西。也許它沒有拿餅乾,我不知道。我有一個問題,爲什麼不工作,是在字符串postData =「」。那些假設是html標籤的名稱或id部分?任何幫助,這是非常讚賞,因爲我很難過,並且將不得不找到一種不同的方式。我想繼續使用WebRequest
和WebResponse
,而不是使用WebBrowser
。如果我不能,那好吧。再次感謝任何幫助!
@Fastlink - 好吧,在發送發佈數據之前,你需要做一個獲取請求bcoz「VIEWSTATE」是發送到發佈數據 – 2013-02-25 04:48:32