C#:使用HttpWebRequest後保持Session,再使用一個HttpWebRequest實現瀏覽、下載等效果

jyh_jack發表於2018-09-06

如何使用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;

 

相關文章