通過應用程序讀取網頁信息的時候,通常需要抓取網頁的數據,但是有一個問題就是很多網頁需要登錄後才能夠獲得頁面數據,那麼就需要保存當前的cookie,在.NET中可以使用CookieContainer 對象來保存登錄後的Cookie信息,每次發送數據的時候加上Cookie信息,就可以解決這個問題了。 #region 同步通過POST方式發送數據 /// <summary> /// 通過POST方式發送數據 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">Post數據</param> /// <param name="cookie">Cookie容器</param> /// <returns></returns> public string SendDataByPost(string Url,string postDataStr,ref CookieContainer cookie) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); if (cookie.Count == 0) { request.CookieContainer = new CookieContainer(); cookie = request.CookieContainer; } else { request.CookieContainer = cookie; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postDataStr.Length; Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); myStreamWriter.Write(postDataStr); myStreamWriter.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString= myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } #endregion #region 同步通過GET方式發送數據 /// <summary> /// 通過GET方式發送數據 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">GET數據</param> /// <param name="cookie">GET容器</param> /// <returns></returns> public string SendDataByGET(string Url, string postDataStr, ref CookieContainer cookie) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url +( postDataStr == "" ? "" : "?") + postDataStr); if (cookie.Count == 0) { request.CookieContainer = new CookieContainer(); cookie = request.CookieContainer; } else { request.CookieContainer = cookie; } request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } #endregion