当前位置: 代码迷 >> 综合 >> HttpWebRequest Post 方式发送 XML数据
  详细解决方案

HttpWebRequest Post 方式发送 XML数据

热度:59   发布时间:2023-12-17 15:26:49.0

昨天开发过程中用到    HttpWebRequest 需要用POST方式发送XML数据 因为XML数据中带有<或着?等特殊符号所以需要用URLEcode 方法进行编码  同时接收页面应该关闭设置ValidateRequest="false"关闭对请求数据的验证

   

   

 public string PostAndGetHTML(string targetURL, string param)
        {

            //formData用于保存提交的信息
            string formData =HttpUtility.UrlEncode(param);

            formData = "strXml=" + formData;
            //把提交的信息转码(post提交必须转码)
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(formData);

 

            //开始创建请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //提交方式:post
            request.ContentType ="application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

           

            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);//将请求的信息写入request
            newStream.Close();
            try

           {
                     //向服务器发送请求
                      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                      Stream s = response.GetResponseStream();
                      StreamReader sr = new StreamReader(s, Encoding.GetEncoding("utf-8"));
                      string strResult = sr.ReadToEnd();

            }
            catch
            {
            }

         }


  相关解决方案