面向接口編程是一種設計思想,無論用什么語言都少不了面向接口開發思想,在軟件開發過程中,常常要調用接口,接下來就是介紹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
(他的頁面右側有個小可愛,啊啊啊啊好想要啊!)