美文网首页
.Net Core 调用post类型的url

.Net Core 调用post类型的url

作者: Rinaloving | 来源:发表于2021-09-16 16:23 被阅读0次
在PostMan中请求如下(参数是一个数组)
Post请求数组参数.png
我们在后台调用的时候要序列化之后才行(这地方没经验,导致我花了一小时时间研究)
// 调用方法
BizBase.Get<BizInfrared>().HasInfraredDevice(JsonConvert.SerializeObject(new string[] { "00124b001fe48891" }));

 string url = string.Format("http://{0}:{1}/api/device/info", serviceIp, servicePort);
 string httpData = HttpMgr.PostData(url, deviceName);
Post 方法
#region PostData
        public static string PostData(string strUrl, string postData)
        {
            return PostData(strUrl, postData, Encoding.UTF8);
        }

        public static string PostData(string strUrl,string postData, Encoding encode, string contentType = "application/json")
        {
            HttpWebRequest hwrq = null;
            HttpWebResponse hwrp = null;
            StreamReader sr = null;
            string strMain = null;
            try
            {
                hwrq = (HttpWebRequest)WebRequest.Create(strUrl);
                hwrq.Method = "post";

                byte[] dataByte = encode.GetBytes(postData);
                hwrq.ContentLength = dataByte.Length;
                Stream sm1 = hwrq.GetRequestStream();
                sm1.Write(dataByte, 0, dataByte.Length);
                sm1.Close();

                hwrq.ContentType = contentType;
                hwrp = (HttpWebResponse)hwrq.GetResponse();
                sr = new StreamReader(hwrp.GetResponseStream(), encode);
                strMain = sr.ReadToEnd();
            }
            catch(Exception ex)
            {
                strMain = null;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr = null;
                }
                if (hwrp != null)
                {
                    hwrp.Close();
                    hwrp = null;
                }
            }
            return strMain;
        }
        #endregion

相关文章

网友评论

      本文标题:.Net Core 调用post类型的url

      本文链接:https://www.haomeiwen.com/subject/zhorgltx.html