这是我用来登录网站并获取我的 cookie 的示例函数
string loginSite(string url, string username, string password)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string cookie = "";
//this values will change depending on the website
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
CookieContainer a = new CookieContainer();
req.CookieContainer = a;
System.Net.ServicePointManager.Expect100Continue = false; // prevents 417 error
using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII)) { writer.Write(values); }
HttpWebResponse c = (HttpWebResponse)req.GetResponse();
Stream ResponseStream = c.GetResponseStream();
StreamReader LeerResult = new StreamReader(ResponseStream);
string Source = LeerResult.ReadToEnd();
foreach (Cookie cook in c.Cookies) { cookie = cookie + cook.ToString() + ";"; }
return cookie;
}
这里有一个调用示例:
string Cookie = loginSite("http://theurl.comlogin.php?s=c29cea718f052eae2c6ed105df2b7172&do=login", "user", "passwd");
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.theurl.com");
//once you got the cookie you add it to the header.
req.Headers.Add("cookie", Cookie);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (Stream respStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(respStream))
{
string s = sr.ReadToEnd();
HtmlReturn = s;
// System.Diagnostics.Debugger.Break();
}
}
使用 Firefox,您可以使用扩展 HTTP-Headers 来了解 post 设置的参数并修改变量值:
string values = "vb_login_username=" + username + "&vb_login_password=" + password
+ "&securitytoken=guest&"
+ "cookieuser=checked&"
+ "do=login";
与目标网站上的参数相匹配。
如果您决定为 firefox 使用 Live-HTTP-HEaders,当您登录网站时,您将从标题中获取帖子信息,如下所示:
GET / HTTP/1.1 主机:www.microsoft.com 用户代理:Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1 接受:text/html,application/xhtml+xml,application/ xml;q=0.9, / ;q=0.8 Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate 连接: keep-alive Cookie:WT_FPC=id=82.144.112.152-154450144.30258861:lv=1351580394112:ss=1351575867559;WT_NVR_RU=0=msdn:1=:2=; omniID=0d2276c2_bbdd_4386_a11d_f8da1dbc5489;MUID=349E06C547426937362B02CC434269B9;MC1=GUID=47b2ed8aeea0de4797d3a40cf549dcbb&HASH=8aed&LV=201210&V=4&LU=1351608258765; A=I&I=AxUFAAAAAAALBwAAukh4HjpMmS4eKtKpWV0ljg!!&V=4; msdn=L=en-US