面向接口編程是一種設計思想,無論用什么語言都少不了面向接口開發思想,在軟件開發過程中,常常要調用接口,接下來就是介紹C#調用其它開發商提供的接口進行獲取數據,http接口方式獲取接口數據。
Get請求數據:
using (var httpClient = new HttpClient())
{
//get
var url = new Uri("接口網絡地址");
// response
var response = httpClient.GetAsync(url).Result;
var data = response.Content.ReadAsStringAsync().Result;
return data;//接口調用成功獲取的數據
}
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");//設置請求頭
