C# Http请求接口数据的两种方式Get and Post
生活随笔
收集整理的這篇文章主要介紹了
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()){ //postvar url = new Uri("接口網絡地址");var body = new FormUrlEncodedContent(new Dictionary<string, string>{{ "參數1", "值1"},{ "參數2", "值2"},{ "參數3", "值3"},{ "參數4", "值4"},});// responsevar 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
(他的頁面右側有個小可愛,啊啊啊啊好想要啊!)
轉載于:https://www.cnblogs.com/baimangguo/p/11341282.html
總結
以上是生活随笔為你收集整理的C# Http请求接口数据的两种方式Get and Post的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (原码反码补码的计算)在一个8位的二进制
- 下一篇: c# char unsigned_dll