在每个人都因为这个问题已经得到回答而感到不安之前。我在网上搜索了如何做到这一点,并尝试了多种方法。通过 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
andWebResponse
而不是使用WebBrowser
. 如果我不能,哦,好吧。再次感谢任何帮助!