Winform程序调用WebApi的方式有很多,本文学习并记录采用HttpClient调用基于GET、POST请求的WebApi的基本方式。WebApi使用之前编写的检索环境检测数据的接口,如下图所示。
调用基于GET请求的无参数WebApi
创建HttpClient实例后调用GetStringAsync函数获取返回json字符串,如果返回的是基本数据,则按需调用格式转换函数将转换返回字符串格式,主要代码如下所示:
string url = @"http://localhost:5098/ECData/ECDataCount";
HttpClient client = new HttpClient();
int result = Convert.ToInt32(client.GetStringAsync(url).Result);
如果返回复杂数据格式,则需预定义数据类,然后调用反序列化函数将返回的json字符串反序列化为指定数据类型的实例对象。需注意的是返回的json字符串中的属性名称的大小写与数据类定义中的属性名称大小写的对应关系。本文测试时使用System.Text.Json反序列化,并配置JsonSerializerOptions忽略大小写。主要代码如下所示:
string url = @"http://localhost:5098/ECData/ECDatas";HttpClient client = new HttpClient();string result = client.GetStringAsync(url).Result;JsonSerializerOptions options = new JsonSerializerOptions();options.PropertyNameCaseInsensitive = true;List< EnvironmentRecord> lstRecords= JsonSerializer.Deserialize<List<EnvironmentRecord>>(result, options);
调用基于GET请求的带参数WebApi
调用基于GET请求的带参数WebApi,其请求参数基本都是附在url最后传递到服务端,此时调用webapi的方式和上一小节一致,如下所示:
string url = @"http://localhost:5098/ECData/List?page=1";
HttpClient client = new HttpClient();
string result = client.GetStringAsync(url).Result;
JsonSerializerOptions options = new JsonSerializerOptions();
options.PropertyNameCaseInsensitive = true;
ListFuncResult lstRecords = JsonSerializer.Deserialize<ListFuncResult>(result, options);
调用基于POST请求的带参数WebApi(通过url传递参数)
调用基于Post请求的带参数WebApi,如果请求参数通过url传递,则调用webapi的方式和上一小节一致,仅调用函数变为PostAsync。主要代码如下所示:
string url = @"http://localhost:5098/ECData/DataTableListByPost?page=1&limit=10";
HttpClient client = new HttpClient();
string result = client.PostAsync(url,null).Result.Content.ReadAsStringAsync().Result;
JsonSerializerOptions options = new JsonSerializerOptions();
options.PropertyNameCaseInsensitive = true;
DataTableFuncResult lstRecords = JsonSerializer.Deserialize<DataTableFuncResult>(result, options);
调用基于POST请求的带参数WebApi(通过请求体传递参数)
通过请求体传递参数的话,需先将参数序列化为字符串,然后创建StringContent对象保存字符串,最终调用PostAsync发送post请求。主要代码如下所示:
string url = @"http://localhost:5098/ECData/DataTableListByPostPlus";
HttpClient client = new HttpClient();QueryCondition condition = new QueryCondition();
condition.page = 1;
condition.limit = 10;var content = new StringContent(JsonSerializer.Serialize<QueryCondition>(condition), Encoding.UTF8);
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");string result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
JsonSerializerOptions options = new JsonSerializerOptions();
options.PropertyNameCaseInsensitive = true;
DataTableFuncResult lstRecords = JsonSerializer.Deserialize<DataTableFuncResult>(result, options);
参考文献:
[1]https://blog.csdn.net/yanzean/article/details/126860942
[2]https://blog.csdn.net/lg_2_lr/article/details
[3]https://www.cnblogs.com/rengke2002/p/7921003.html