C# Post发送 接受Xml

 //组合xml内容
            StringBuilder strBuilder = new StringBuilder();
            var par= @"<xml>
                        <appid>wx2421b1c4370ec43b</appid>
                        <attach>支付测试</attach>
                        <body>H5支付测试</body>
                        <mch_id>10000100</mch_id>
                        <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
                        <notify_url>http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url>
                        <openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid>
                        <out_trade_no>1415659990</out_trade_no>
                        <spbill_create_ip>14.23.150.211</spbill_create_ip>
                        <total_fee>1</total_fee>
                        <trade_type>MWEB</trade_type>
                        <scene_info>{""h5_info"": {""type"":""IOS"",""app_name"": ""王者荣耀"",""package_name"": ""com.tencent.tmgp.sgame""}}</scene_info>
                        <sign>0CB01533B8C1EF103065174F50BCA001</sign>
                       </xml> ";
            strBuilder.Append(par);
            string data = strBuilder.ToString();
            //进行utf-8编码
            var encoding = Encoding.GetEncoding("utf-8");
            byte[] buffer = encoding.GetBytes(data);
            //根据webURL创建HttpWebRequest对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            //request.Headers.Add("charset:utf-8");            
            request.ContentLength = buffer.Length;
            request.ContentType = "text/xml";

            StreamWriter myWriter = null;
            try
            {
                myWriter = new StreamWriter(request.GetRequestStream());
                myWriter.Write(data);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                myWriter.Close();
            }
            //读取服务器返回的信息
            HttpWebResponse objResponse = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
            {
                string result = string.Empty;
                result = sr.ReadToEnd();
                Console.WriteLine(result);
                var resultStr = XElement.Parse("result");
                var result_code = resultStr.Element("return_code").Value;
                var result_msg = resultStr.Element("return_msg").Value;
            }

 

C# Post发送 接受Xml

上一篇:C#基础操作符详解(下)


下一篇:安装Windows和Ubuntu双系统