C#使用post发送数据

 

    #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
posted @ 2009-03-01 15:04  怪_怪  阅读(922)  评论(0编辑  收藏  举报