模拟登陆的原理很简单,就是发送一个Http 请求服务器获得响应,然后客户端获取到cookie即可实现模拟登陆,比如一些抢票软件的原理无非也是这样模拟客户端的cookie 然后发送请求去抢票,然后12306 本文将演示如何用C# 来实现模拟登陆的,推荐一款工具Fiddler,这是一款监听http 请求的利器。废话不多说,我就以博客园为例来实现模拟登陆。首先我登陆博客园 http://passport.cnblogs.com/login.aspx 输入用户名和密码点登陆 就会看到Fiddler 上的相关信息:
Ok,我首先需要发送一个http 请求 ,这个请求时POST的方式,然后用户名和密码就是POST的数据。代码如下:
static cookieContainer Getcookie(string postString, string postUrl)
{
cookieContainer cookie = new cookieContainer();
HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//创建http 请求
httpRequset.cookieContainer = cookie;//设置cookie
httpRequset.Method = "POST";//POST 提交
httpRequset.KeepAlive = true;
httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
httpRequset.Accept = "text/html, application/xhtml+xml, **";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Method = "GET";
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (Stream responsestream = httpResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8))
{
content = sr.ReadToEnd();
}
}
return content;
}
OK 下面是调用 我写的是一个控制台程序:
static void Main(string[] args)
{
string loginstr = "{要post 的登陆数据包括用户名和密码}";
//从登陆的地址获取cookie
cookieContainer cookie = Getcookie(loginstr, "http://passport.cnblogs.com/login.aspx");
//这个是进入后台地址
Console.WriteLine(GetContent(cookie, "http://i.cnblogs.com/EditPosts.aspx"));
Console.Read();
}
可以看到我已经进入了后台了:
如果我是没有登陆的情况下进入这个地址是这样的:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



