提交Html请求并保存身份信息
//创建请求
HttpWebRequest mRequest = WebRequest.Create("http://www.a.com/Login.aspx") as HttpWebRequest;
mRequest.Method = "POST";
mRequest.ContentType = "application/x-www-form-urlencoded";
mRequest.AllowAutoRedirect = false;
mRequest.CookieContainer = new CookieContainer();
string strPostData = "username=aaa&userpwd=bbb";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strPostData);
mRequest.ContentLength = buffer.Length;
//发送数据
Stream stream = mRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
//得到响应
wr = (HttpWebResponse)mRequest.GetResponse();
CookieCollection cc = mRequest.CookieContainer.GetCookies(mRequest.Address);
//读取响应内容
sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
//显示在浏览器中
browser.Navigate("about:blank");
browser.DocumentText = sr.ReadToEnd();
//关闭
sr.Close();
wr.Close();
再次提交时,将cc加入到请求对象的CookieContainer中。
HttpWebRequest mRequest = WebRequest.Create("http://www.a.com/Login.aspx") as HttpWebRequest;
mRequest.Method = "POST";
mRequest.ContentType = "application/x-www-form-urlencoded";
mRequest.AllowAutoRedirect = false;
mRequest.CookieContainer = new CookieContainer();
string strPostData = "username=aaa&userpwd=bbb";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strPostData);
mRequest.ContentLength = buffer.Length;
//发送数据
Stream stream = mRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
//得到响应
wr = (HttpWebResponse)mRequest.GetResponse();
CookieCollection cc = mRequest.CookieContainer.GetCookies(mRequest.Address);
//读取响应内容
sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
//显示在浏览器中
browser.Navigate("about:blank");
browser.DocumentText = sr.ReadToEnd();
//关闭
sr.Close();
wr.Close();