您的位置:首页 > 理论基础 > 计算机网络

使用C#的HttpWebRequest模拟登陆网站(续)

2011-12-20 18:25 926 查看
上一篇文章中我们讲了,如何采用程序模拟登录网站,并获取登录后网站的内容,今天在此基础上继续将,通过程序登录了网站后而直接进入登录后的页面。

首先还是发起一个启用一个web会话,然后发送模拟数据请求,获取会话的CooKie,再根据该CooKie将其写入到本地,通过程序直接打开登录后的页面。

该功能可用于无法修改第三方系统源代码而要做系统单点登录。

我们先在HTMLHelper类中添加一个方法:

View Code

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]

public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

HttpHeader header = new HttpHeader();
header.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
header.contentType = "application/x-www-form-urlencoded";
header.method = "POST";
header.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
header.maxTry = 300;

CookieCollection mycookie = HTMLHelper.GetCookieCollection("http://www.renren.com/PLogin.do",
"email=aaa%40163.com&password=111&icode=&origURL=http%3A%2F%2Fwww.renren.com%2Fhome&domain=renren.com&key_id=1&_rtk=90484476", header);

foreach (Cookie cookie in mycookie) //将cookie设置为浏览的cookie
{

InternetSetCookie(

"http://" + cookie.Domain.ToString(),

cookie.Name.ToString(),

cookie.Value.ToString() + ";expires=Sun,22-Feb-2099 00:00:00 GMT");

}
System.Diagnostics.Process.Start("http://guide.renren.com/guide");


这样即可直接通过程序打开登录后的页面:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: