HttpWebRequest 保持session

chenbin520發表於2012-05-12

 通過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();
        }
    }


相關文章