您的位置:首页 > 运维架构 > 网站架构

基于c#实现网站的自动登陆

2014-05-24 20:03 459 查看
实现校园网的网关自动认证。

从网上找到了两种思路:一种是模拟网站的点击动作,实现自动登录。第二种是自动向登录目标发送登陆字符串。

下面是源码:

第一种:

//webBrowser1.Url =new Uri("http://);

////定义html元素 通过Name获取控件值

//HtmlElement tbUserid = webBrowser1.Document.All["DDDDD"];

//HtmlElement tbPasswd = webBrowser1.Document.All["upass"];

//HtmlElement btnSubmit = webBrowser1.Document.All["0MKKey"];

//////定义html元素 通过ID获取控件值 (用户名 密码 登录按钮)

////HtmlElement tbUserid = webBrowser1.Document.GetElementById("DDDDD");

////HtmlElement tbPasswd = webBrowser1.Document.GetElementById("upass");

////HtmlElement btnSubmit = webBrowser1.Document.GetElementById("0MKKey");

////三个元素其一为空返回 加载后才执行赋值 否则会出现为null值的崩溃错误

//if (tbUserid == null || tbPasswd == null || btnSubmit == null)

//{

// return;

//}

////设置元素value属性值 (用户名 密码值)

//tbUserid.SetAttribute("value","111111");

//tbPasswd.SetAttribute("value", "111111");

////执行元素的方法:如click submit

//btnSubmit.InvokeMember("click");

第二种:

string username = "11";//用户名

string password = "1111";//密码

//新建一个用于保存cookies的容器

CookieContainer container = new CookieContainer();

//拼接post数据DDDDD=11&upass=1111&0MKKey=%C1%AC%BD%D3%CD%F8%C2%E7

string postData = ("DDDDD=" + username);

postData += ("&upass=" + password);

postData += ("&0MKKey=%C1%AC%BD%D3%CD%F8%C2%E7");

ASCIIEncoding encoding = new ASCIIEncoding();

byte[] data = encoding.GetBytes(postData);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://");

request.Method = "Post";

request.ContentType = "application/x-www-form-urlencoded";

request.ContentLength = data.Length;

request.KeepAlive = true;

request.CookieContainer = container; //返回的cookie会附加在这个容器里面

//发送数据

Stream newStream = request.GetRequestStream();

newStream.Write(data, 0, data.Length);

newStream.Close();

////以下俩句不可缺少

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

response.Cookies = container.GetCookies(request.RequestUri);

StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);

string content = reader.ReadToEnd();

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