1. 程式人生 > >MVC後臺POST方法呼叫遠端API介面

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;