C# Http請求接口數據的兩種方式Get and Post


面向接口編程是一種設計思想,無論用什么語言都少不了面向接口開發思想,在軟件開發過程中,常常要調用接口,接下來就是介紹C#調用其它開發商提供的接口進行獲取數據,http接口方式獲取接口數據。

Get請求數據:

1 using (var httpClient = new HttpClient())
2            {               
3                //get
4                var url = new Uri("接口網絡地址");
5                // response
6                var response = httpClient.GetAsync(url).Result;
7                var data = response.Content.ReadAsStringAsync().Result;
8               return data;//接口調用成功獲取的數據
9            }

 

Post請求數據:

using (var httpClient = new HttpClient())
            {            
                //post
                var url = new Uri("接口網絡地址");
                var body = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "參數1", "值1"},
                    { "參數2", "值2"},
                    { "參數3", "值3"},
                    { "參數4", "值4"},
                });
                // response
                var response = httpClient.PostAsync(url, body).Result; 
                var data = response.Content.ReadAsStringAsync().Result;
                return data;//接口調用成功數據
            }

 

如果接口調用需要傳請求頭可以使用如下代碼設置請求頭:

httpClient.DefaultRequestHeaders.Add("Accept", "application/json");//設置請求頭

轉自:https://www.cnblogs.com/jiangxifanzhouyudu/p/8992574.html

(他的頁面右側有個小可愛,啊啊啊啊好想要啊!)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM