MVC后台POST方法调用远程API接口

        //post方法调用接口
        public void PostFunction(string devID)
        {
            string url = "";//接口URL
            string strPostdata = "{\"id\":\"rt02\"}";//注意!双引号
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.ContentType = "application/json";
            byte[] buffer = encoding.GetBytes(strPostdata);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            var res = "";
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
            {
                res = reader.ReadToEnd();//读取全部
            }
        }

如果提示缺少引用,选中类名,alt + shift + F10 就可以了。

用到的引用:

using System.IO;

using System.Net;

using System.Text;

你可能感兴趣的:(c#,asp.net)