面向接口编程是一种设计思想,无论用什么语言都少不了面向接口开发思想,在软件开发过程中,常常要调用接口,接下来就是介绍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");//设置请求头