用C#使用HttpWebRequest Post数据时如何保持Session
利用WebClient, HttpWebRequest向某址POST数据,这个都很方便,都有的网站需要保持SESSION才能进行下一步想要的操作。保持SESSION,关键在于如何保持住Cookie不变。
代码如下:
CookieContainer cookie;
private void button1_Click(object sender, System.EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/new/index.php");
request.CookieContainer = cookie;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
this.richTextBox1.Text = reader.ReadToEnd();
stream.Close();
reader.Close();
response.Close();
}
private void Form1_Load(object sender, System.EventArgs e)
{
cookie = new CookieContainer();
}