C# HttpWebRequest 方式提交資料,引數為普通鍵值對

weixin_34262482發表於2013-03-18
private string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //轉化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//寫入引數
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            return ret;
        }

  

paramData格式為:a=1&b=2等;

-------------------------
下面為伺服器端接收方法:
載入事件中:
//對應PostWebRequest方法
            //Response.Write(string.Format("<?xml version=\"1.0\"?><params><title>{0}</title></params>",Request["a"]));

  

相關文章