C# 向Http服务器送出 POST 请求

       //向Http服务器送出 POST 请求  
        public string m_PostSubmit(string strUrl,string strParam)
        {
            string strResult = "error";
            try
            {
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(strUrl);
                Encoding encoding = Encoding.UTF8;
                //encoding.GetBytes(postData);
                byte[] bs = Encoding.ASCII.GetBytes(strParam);
                string responseData = System.String.Empty;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = bs.Length;
                try
                {
                    using (System.IO.Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                        reqStream.Close();
                    }
                    using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse())
                    {
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
                        {
                            responseData = reader.ReadToEnd().ToString();
                            strResult = responseData;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    strResult = "error:" + ex.Message;//返回异常信息
                }
            }
            catch (System.Exception ex)
            {
                strResult = "error:" + ex.Message;//返回异常信息
            }
            return strResult;
        }

调用示例:

string strURL = "http://localhost/WinformSubmit.php";

//string param = string.Format("do=login&u={0}&p={1}", username, password); //参数的另一种写法

string strCallerId="1398888888";

string strParam = "callerid=" + strCallerId ;
string strResult = this.m_PostSubmit(strUrl,strParam);

http部分

WinformSubmit.php 页

if($_POST['callerid']=="139"){
  echo("是");
}
else {
  echo("否");
}

  

posted @ 2016-06-20 10:57  海乐学习  阅读(6654)  评论(0编辑  收藏  举报