C#:使用HttpWebRequest后保持Session,再使用一个HttpWebRequest实现浏览、下载等效果

如何使用HttpWebRequest后登录网站后,再使用一个HttpWebRequest实现浏览、下载等效果?

两个request之前都是单独的请求,需要保持Session,然而Session的保持需要Cookies,所以给两个request同一个CookieContainer就可以了。

样例如下,注意写注释的三行代码,

CookieContainer cc = new CookieContainer(); //创建一个容器

request.CookieContainer = cc; //给第一个request指定容器

request2.CookieContainer = cc; //给第二个request指定同一个容器

CookieContainer cc = new CookieContainer(); //创建一个容器
HttpWebRequest request = null;
string url = "http://?????.com/SvltLogin";
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cc; //给第一个request指定容器
request.Method = "POST";
request.Accept = "*/*;";
request.UserAgent = "Mozilla/5.0";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
request.KeepAlive = true;
 
string postData = string.Format("txtUsr_id=00000001&txtPassword=mima"); 
byte[] postdatabyte = Encoding.GetEncoding("gbk").GetBytes(postData);
request.ContentLength = postdatabyte.Length;
using (Stream stream = request.GetRequestStream())
{
	stream.Write(postdatabyte, 0, postdatabyte.Length);
}
 
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 
string strWebData = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gbk")))
{
	strWebData = reader.ReadToEnd();
}
richTextBox1.Text = strWebData;


//开始第二个Request
url = "http://?????.com/abcd";
HttpWebRequest request2 = WebRequest.Create(url) as HttpWebRequest;
request2.CookieContainer = cc; //给第二个request指定同一个容器
HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;

 

你可能感兴趣的:(C#)