c#访问webapi以及获取

本文详细介绍了使用C#通过HTTP POST请求发送不同格式数据的方法,包括XML、纯文本、JSON和表单数据。提供了完整的代码示例,展示了如何设置请求头,构造请求体并读取响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提交post

#region XML方式提交
        public static void XML() {
            HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://localhost:30447/api/product/showname");
            wReq.Method = "POST";
            wReq.ContentType = "text/xml";
            wReq.Headers.Add("charset:utf-8");
            var encoding = Encoding.GetEncoding("utf-8");

            if (GetXml() != null)
            {
                byte[] buffer = encoding.GetBytes(GetXml());
                wReq.ContentLength = buffer.Length;
                wReq.GetRequestStream().Write(buffer, 0, buffer.Length);
            }
            else {
                wReq.ContentLength = 0;
            }
        }
        /// <summary>
        /// 发送的XML
        /// </summary>
        /// <returns></returns>
        public static string GetXml() {
            StringBuilder str = new StringBuilder();
            str.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            str.Append("<Product>");
            str.Append("<Id>456</Id>");
            str.Append("<Name>ASDD</Name>");
            str.Append("<Categroy>QWER</Categroy>");
            str.Append("<Price>456</Price>");
            str.Append("</Product>");
            return str.ToString();
        }
        #endregion

        #region Text提交方法
        public static void TEXT() {
            HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://localhost:30447/api/product/showname");
            wReq.Method = "POST";
            wReq.ContentType = "text/plain";

            byte[] data = Encoding.Default.GetBytes("Id:798,Name:\"QW\",Categroy:\"ajsdkf\",Price:789");
            wReq.ContentLength = data.Length;
            Stream reqStream = wReq.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();
            using (StreamReader sr = new StreamReader(wReq.GetResponse().GetResponseStream()))
            {
                string result = sr.ReadToEnd();
            }
        }
        #endregion
        #region JSON发送方法
        /// <summary>
        /// JSON发送方法
        /// </summary>
        public static void Json() {
            HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://localhost:30447/api/product/showname");
            wReq.Method = "POST";
            wReq.ContentType = "application/JSON";

            byte[] data = Encoding.Default.GetBytes("{Id:123,Name:\"zwy\",Categroy:\"ajsdkf\",Price:123}");
            wReq.ContentLength = data.Length;
            Stream reqStream = wReq.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();
            using (StreamReader sr = new StreamReader(wReq.GetResponse().GetResponseStream()))
            {
                string result = sr.ReadToEnd();
            }
        }
        #endregion
        #region Form提交

        public static void Froms()
        {
            HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://localhost:30447/api/product/showname");
            wReq.Method = "POST";
            wReq.ContentType = "application/x-www-form-urlencoded";

            string str = "Id:123,Name:\"zwy\",Categroy:\"ajsdkf\",Price:123";

            byte[] data = Encoding.Default.GetBytes(str);
            wReq.ContentLength = data.Length;
            Stream reqStream = wReq.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            reqStream.Close();
            using (StreamReader sr = new StreamReader(wReq.GetResponse().GetResponseStream()))
            {
                string result = sr.ReadToEnd();
            }
        }

        #endregion

获取

[HttpPost]
        public Product ShowName()
        {
            var prod=new Product();

            var s = System.Web.HttpContext.Current.Request.InputStream;
            var b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            var str = Encoding.UTF8.GetString(b);
            try
            {
                //如果不是JSON报错
                var serializer = new JavaScriptSerializer();
                dynamic obj = serializer.Deserialize(str, typeof(object));
                //prod = serializer.Deserialize<Product>(str);

            }
            catch (Exception ex)
            {
                try
                {
                    //如果不是xml,也不是json
                    var d = new XmlDocument();
                    d.LoadXml(str);
                    //prod=  DeserializeToObject<Product>(str);
                }
                catch (Exception e)
                {
                    //text文本
                    string index = str;
                }
     
            }
            return prod;
        }

转载于:https://www.cnblogs.com/zwyAndDong/p/8405695.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值