1. 程式人生 > >【C#MVC】 使用HttpWebRequest訪問外部API,並返回json資訊 (Access_Key)

【C#MVC】 使用HttpWebRequest訪問外部API,並返回json資訊 (Access_Key)

在c#中呼叫外部API或者自己系統的API都是很簡單的,這裡提供使用HttpWebRequest的方式訪問外部API,自定義了頭部Access_key.
若外部系統沒有此安全驗證,可以去掉。

        public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
        {
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create
(URL); request.Method = "post"; request.Headers.Add("access_key", "your access_key"); request.Accept = "application/json"; request.ContentType = "application/json; charset=utf-8"; byte[] buffer = Encoding.ASCII.GetBytes(strPostdata); request.ContentLength
= buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) //System.Text.Encoding.GetEncoding
(strEncoding) { return reader.ReadToEnd(); } }