在實際編程中,,可能需要讀取特定網頁的信息,但很多網站需要用戶登錄后,,才能夠獲取相關的頁面內容,,這就需要編程者先臨時存儲當前的cookie,在C#中可以使用CookieContainer 對象來保存登錄后的Cookie信息,,這樣,,在每次發(fā)送數(shù)據的時候,附加上Cookie信息,,就可以了,。 #region 同步通過POST方式發(fā)送數(shù)據 /// <summary> /// 通過POST方式發(fā)送數(shù)據 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">Post數(shù)據</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方式發(fā)送數(shù)據 /// <summary> /// 通過GET方式發(fā)送數(shù)據 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">GET數(shù)據</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 |
|