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

时间:2024-08-22 18:36:50
       //向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("否");
}