面向接口编程是一种设计思想,无论用什么语言都少不了面向接口开发思想,在软件开发过程中,常常要调用接口,接下来就是介绍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
(他的页面右侧有个小可爱,啊啊啊啊好想要啊!)