C# 使用HttpWebRequest提交ASP.NET表单并保持Session和Cookie
由于种种原因,我们有时需要从互联网上抓取一些资料,有些页面可以直接打开,而有些页面必登录之后才能打开。本文介绍的是使用 HttpWebRequest 和 HttpWebResponse 自动填写提交 ASP.NET 表单并保持 Session 和 Cookie 的一个完整的例子。
这里涉及到3个页面:MyLogin.aspx,LoginOK.htm,Default.aspx:
1)MyLogin.aspx 页面
这里涉及到3个页面:MyLogin.aspx,LoginOK.htm,Default.aspx:
1)MyLogin.aspx 页面
MyLogin.aspx 页面是登录页面,如果用户名和密码正确会生成 Session 和 Cookie(LoginSession、LoginCookie),然后转向 LoginOK.htm 页面。
2)LoginOK.htm 页面
2)LoginOK.htm 页面
LoginOK.htm 页面是一个跳转页面,几秒钟后会自动跳转到 Default.aspx 页面。
3)Default.aspx 页面
3)Default.aspx 页面
Default.aspx 页面是主界面,打开主界面时会判断 LoginSession 和 LoginCookie 的值是否正确,并把 Session 和 Cookie 的值显示出来。
提交ASP.NET表单(即完成自动登录)的代码如下:
try
{
CookieContainer cookieContainer = new CookieContainer();
///////////////////////////////////////////////////
// 1. 打开 MyLogin.aspx 页面,获得 GetVeiwState & EventValidation
///////////////////////////////////////////////////
// 设置打开页面的参数
string URI = "http://localhost:1165/WebTest/MyLogin.aspx";
HttpWebRequest request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
// 接收返回的页面
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream,Encoding.UTF8);
string srcString = reader.ReadToEnd();
// 获取页面的 VeiwState
string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("\"", i);
string viewState = srcString.Substring(i, j - i);
// 获取页面的 EventValidation
string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("\"", i);
string eventValidation = srcString.Substring(i, j - i);
提交ASP.NET表单(即完成自动登录)的代码如下:
try
{
CookieContainer cookieContainer = new CookieContainer();
///////////////////////////////////////////////////
// 1. 打开 MyLogin.aspx 页面,获得 GetVeiwState & EventValidation
///////////////////////////////////////////////////
// 设置打开页面的参数
string URI = "http://localhost:1165/WebTest/MyLogin.aspx";
HttpWebRequest request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
// 接收返回的页面
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream,Encoding.UTF8);
string srcString = reader.ReadToEnd();
// 获取页面的 VeiwState
string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("\"", i);
string viewState = srcString.Substring(i, j - i);
// 获取页面的 EventValidation
string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("\"", i);
string eventValidation = srcString.Substring(i, j - i);
///////////////////////////////////////////////////
// 2. 自动填充并提交 MyLogin.aspx 页面
///////////////////////////////////////////////////
// 提交按钮的文本
string submitButton = "登录";
// 2. 自动填充并提交 MyLogin.aspx 页面
///////////////////////////////////////////////////
// 提交按钮的文本
string submitButton = "登录";
// 用户名和密码
string userName = "1";
string password = "1";
string userName = "1";
string password = "1";
// 将文本转换成 URL 编码字符串
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
// 要提交的字符串数据。格式形如:user=uesr1&password=123
string formatString =
"userName={0}&password={1}&loginButton={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
string postString =
string.Format(formatString, userName, password, submitButton, viewState, eventValidation);
string formatString =
"userName={0}&password={1}&loginButton={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
string postString =
string.Format(formatString, userName, password, submitButton, viewState, eventValidation);
// 将提交的字符串数据转换成字节数组
byte[] postData = Encoding.ASCII.GetBytes(postString);
byte[] postData = Encoding.ASCII.GetBytes(postString);
// 设置提交的相关参数
request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
request.ContentLength = postData.Length;
request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
request.ContentLength = postData.Length;
// 提交请求数据
System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
// 接收返回的页面
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream,Encoding.GetEncoding("GB2312"));
srcString = reader.ReadToEnd();
foreach (Cookie cookie in response.Cookies)
cookieContainer.Add(cookie);
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream,Encoding.GetEncoding("GB2312"));
srcString = reader.ReadToEnd();
foreach (Cookie cookie in response.Cookies)
cookieContainer.Add(cookie);
///////////////////////////////////////////////////
// 3. 打开 Default.aspx 页面
///////////////////////////////////////////////////
// 设置打开页面的参数
URI = "http://localhost:1165/WebTest/Default.aspx";
request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.CookieContainer = cookieContainer;
// 3. 打开 Default.aspx 页面
///////////////////////////////////////////////////
// 设置打开页面的参数
URI = "http://localhost:1165/WebTest/Default.aspx";
request = WebRequest.Create(URI) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.CookieContainer = cookieContainer;
// 接收返回的页面
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
///////////////////////////////////////////////////
// 4. 分析返回的页面
///////////////////////////////////////////////////
//
}
catch (WebException we)
{
string msg = we.Message;
}
之所以能够保持 Session 和 Cookie 是因为使用了 Cookie 容器(CookieContainer),见红色的代码部分。
本文所有源代码:https://files.cnblogs.com/gotolnc/AutoPostWithCookies.rar// 4. 分析返回的页面
///////////////////////////////////////////////////
//
}
catch (WebException we)
{
string msg = we.Message;
}
之所以能够保持 Session 和 Cookie 是因为使用了 Cookie 容器(CookieContainer),见红色的代码部分。