使用 HttpWebRequest 向网站提交数据的方法 使用 HttpWebRequest 向网站提交数据的方法

2016-06-11

//参数拼装
string SIPdate = "sip_A=" + appId + "&sip_apiname=" + apiname;
//参数拼装
string apidate = "&userId=" + appUserId + "&userIdPws=" + userIdPws;

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postdata = encoding.GetBytes(SIPdate + apidate);//所有要传参数拼装


//这里使用正式环境URL,测试环境使用http://test.ktonsoft.com/test

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://test.ktonsoft.com/test");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = postdata.Length;
Stream newStream = myRequest.GetRequestStream();
// 发送数据
newStream.Write(postdata, 0, postdata.Length);
newStream.Close();
// 接收返回数据
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
  string status = myResponse.Headers.Get("sip_status");//获得接口返回状态码
  if (status != null)
     {
      //返回结果为成功的情况
       if ("9999".Equals(status))
        {
          StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
          string content = reader.ReadToEnd();
          //解析接口返回值,返回是XML格式
          XmlDocument xmlDoc = new XmlDocument();
          xmlDoc.LoadXml(content);
          XmlNode xn = xmlDoc.SelectSingleNode("String");
          XmlElement xe = (XmlElement)xn;
          string result = xe.InnerText;
          setMessage(result);//用于页面显示
         }
         //返回错误信息解析,此处为了说明各返回值
        else
         {
          setMessage(status);//用于页面显示
         }
     }
  }

 

///<summary>
///根据传入的值,返回相应的结果
///</summary>
private void setMessage(String result)
{
    switch (Int32.Parse(result))
    {
      case 1: messages = "成功"; break;
      case 0: messages = "失败,错误信息A"; break;
     case -1: messages = "失败,错误信息B:"; break;
     case -2: messages = "失败,错误信息C:"; break;
     default: messages = "失败,错误信息D:"; break;
    }
 }