有些时候我们需要模拟操作网页,首先我们需要模拟登录。今天我就讲一下模拟登录并且获取源文件的方法。
首先我们要下载一个抓包工具。我用的Fiddler,抓取登录的信息。也可以使用浏览器自带的开发者工具,把注释“//以上信息在监听请求的时候都有的直接复制过来”上面的都对比一下。具体使用方法不在这里讲解了。如果使用有问题可以私信我。
这里讲一下登录的源码。
//获取cookie方法
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.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0";
httpRequset.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在监听请求的时候都有的直接复制过来
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString);
httpRequset.ContentLength = bytes.Length;
Stream stream = httpRequset.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();//以上是POST数据的写入
HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();//获得 服务端响应
return cookie;//拿到cookie
}
//连接方法
static string GetContent(CookieContainer cookie, string url)
{
string content;
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.CookieContainer = cookie;
httpRequest.Referer = url;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0";
httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
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;
}
//单机获取,并在textbox里面展现出来
private void button1_Click(object sender, EventArgs e)
{
//抓取信息
string loginstr = "";
//从登陆的地址获取cookie
CookieContainer cookie = GetCookie(loginstr, "");
//这个是进入后台地址
//webBrowser1.DocumentText = GetContent(cookie, "");
textBox1.Text = GetContent(cookie, "");
}
最后一条在textbox里面显示,只是测试是否登录成功,在textbox里面可以看到登录后的源码,就说明登录成功了。