C#通過webRequest保持在同一Session中Post資料

crabo發表於2005-12-08

WebClient無疑是C# 中訪問web最簡易快捷的方法:PostData/DownloadFile 為眾人所傾倒.
但有些要求Session保持的情況,則WebClient鞭長莫及了.

http://blog.csdn.net/crabo/

定義全域性變數:
HttpWebRequest craboRequest=null;
CookieContainer craboCookie = new CookieContainer();

private string SendRequest(string _url,string _requestString)
  {
   try
   {
    #region Request
    byte[] requestBytes  =  System.Text.Encoding.GetEncoding("GB2312").GetBytes(_requestString); 
    craboRequest= (HttpWebRequest)WebRequest.Create(_url);  
    craboRequest.ContentType  =  "application/x-www-form-urlencoded";  
    craboRequest.ContentLength= requestBytes.Length;
    craboRequest.Method  =  "POST";  
    craboRequest.CookieContainer  =  craboCookie; 
    using(Stream writer =  craboRequest.GetRequestStream()) 
    { 
     writer.Write(requestBytes,0,requestBytes.Length);
    }
    #endregion
}

相關文章