通过HttpWebRequest获取网页内容并保持session,最主要的就是存储cookie。这里使用了一个静态变量m_Cookie用来存储cookie的内容。第二次请求网页的时候把cookie传送过去,这样就可以保持session。
- public partial class RequestPage : System.Web.UI.Page
- {
- private static CookieContainer m_Cookie = new CookieContainer();
- private string m_Url = "http://localhost/HttpRequestTest/SessionPage.aspx";
- protected void Page_Load(object sender, EventArgs e)
- {
- string content = GetPageContent();
- //string content = GetPageContent(m_Url);
- Label1.Text = content;
- }
- /// <summary>
- /// 获取页面内容,保存CookieHeader
- /// </summary>
- /// <returns></returns>
- private string GetPageContent()
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_Url);
- request.CookieContainer = m_Cookie;
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(m_Url));
- m_Cookie.SetCookies(new Uri(m_Url), cookieheader);
- Stream stream = response.GetResponseStream();
- StreamReader reader = new StreamReader(stream);
- string result = reader.ReadToEnd();
- stream.Close();
- reader.Close();
- response.Close();
- return result;
- }
- /// <summary>
- /// 获取页面内容,存储CookieContainer
- /// </summary>
- /// <param name="url">被请求页面的url</param>
- /// <returns>返回页面内容</returns>
- public string GetPageContent(string url)
- {
- StringBuilder result = new StringBuilder("");
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); ;
- HttpWebResponse reponse = null;
- try
- {
- request.CookieContainer = m_Cookie;
- reponse = (HttpWebResponse)request.GetResponse();
- m_Cookie = request.CookieContainer;
- Stream rspStream = reponse.GetResponseStream();
- StreamReader sr = new StreamReader(rspStream, System.Text.Encoding.Default);
- //获取数据
- Char[] read = new Char[256];
- int count = sr.Read(read, 0, 256);
- while (count > 0)
- {
- result.Append(read, 0, count);
- count = sr.Read(read, 0, 256);
- }
- }
- catch (Exception e)
- {
- result.Append(e.Message);
- }
- finally
- {
- if (reponse != null)
- {
- reponse.Close();
- }
- }
- return result.ToString();
- }
- }