当前位置: 首页 > news >正文

WinFrom调用webapi接口方法及其应用实例

1.WinFrom调用webapi接口方法

最近项目要在winfrom项目中调用webAPI,故在网上查找资料,找到了一个WinFrom调用webapi接口的通用方法,关键代码:

 #region WinFrom调用webapi接口通用方法private async Task<string> InvokeWebapi(string url, string api, string type, Dictionary<string, string> dics){string result = string.Empty;HttpClient client = new HttpClient();client.DefaultRequestHeaders.Add("authorization", "Basic YWRtaW46cGFzc3dvcmRAcmljZW50LmNvbQ==");//basic编码后授权码client.BaseAddress = new Uri(url);client.Timeout = TimeSpan.FromSeconds(510);if (type.ToLower() == "put"){HttpResponseMessage response;//包含复杂类型if (dics.Keys.Contains("input")){if (dics != null){foreach (var item in dics.Keys){api = api.Replace(item, dics[item]).Replace("{", "").Replace("}", "");}}var contents = new StringContent(dics["input"], Encoding.UTF8, "application/json");response = client.PutAsync(api, contents).Result;if (response.IsSuccessStatusCode){result = await response.Content.ReadAsStringAsync();return result;}return result;}var content = new FormUrlEncodedContent(dics);response = client.PutAsync(api, content).Result;if (response.IsSuccessStatusCode){result = await response.Content.ReadAsStringAsync();return result;}}else if (type.ToLower() == "post"){var content = new FormUrlEncodedContent(dics);HttpResponseMessage response = client.PostAsync(api, content).Result;if (response.IsSuccessStatusCode){result = await response.Content.ReadAsStringAsync();return result;}}else if (type.ToLower() == "get"){HttpResponseMessage response = client.GetAsync(api).Result;if (response.IsSuccessStatusCode){result = await response.Content.ReadAsStringAsync();return result;}}else{return result;}return result;}#endregion   

2.应用实例

创建一个名为callWebAPI的窗体项目,在窗体加两个textBox。下面实例主要是调用webAPI的方法获取数据存为json格式,然后将json格式的数据从文件中读取出来。调用代码如下:

 private async void callWebAPI_Load(object sender, EventArgs e){#region 调用webapi并存为json格式文件string api = "";string url = "http://10.3.11.2/SimploWebApi/api/LASER_System/LASER_GetLineShowConfig?typeString=2";Dictionary<string, string> dics = new Dictionary<string, string>();Task<string> task = InvokeWebapi(url, api, "post", dics);string result = task.Result;//textBox1.Text = result;if (result != null){JObject jsonObj = null;jsonObj = JObject.Parse(result);DataInfo info = new DataInfo();info.statusCode = Convert.ToInt32(jsonObj["statusCode"]);//info.message = jsonObj["message"].ToString();if (info.statusCode == 0){JArray jlist = JArray.Parse(jsonObj["Data"].ToString());string json = JsonConvert.SerializeObject(jlist, Formatting.Indented);//File.WriteAllText("Standard.json", json);//将数据存为json格式for (int i = 0; i < jlist.Count; ++i)  //遍历JArray  {                     JObject tempo = JObject.Parse(jlist[i].ToString());textBox1.Text += tempo["line"].ToString();                    }}}#endregion#region  获取json文件数据// 读取JSON文件内容string jsonFilePath = "Standard.json";string jsons = File.ReadAllText(jsonFilePath);// 反序列化JSON到对象Standard standard = JsonConvert.DeserializeObject<Standard>(jsons);textBox2.Text = standard.line + "," + standard.linePlace;#endregion}

以上实例还需建立DataInfo类和Standard类

DataInfo类

DataInfo info = new DataInfo();

 public class DataInfo{public int statusCode { get; set; }public string message { get; set; }     }

Standard类

 Standard standard = JsonConvert.DeserializeObject<Standard>(jsons);

  public class Standard{public string line { get; set; }public string linePlace { get; set; }     }

以上实例用了json,所以需要引用Newtonsoft.Json.dll(具体引用方法见以前文章)

using Newtonsoft.Json;

Standard.json文件

{"line": "B10","linePlace": "CQ_1", }

补充:

get的传参方式

            string api = "";string sWo = "1025";          string url = "http://10.1.1.1/api/MES/API_GetLaserAOIParm?sWo=" + sWo + "";Dictionary<string, string> dics = new Dictionary<string, string>();          Task<string> task = InvokeWebapi(url, api, "post", dics);string result = task.Result;

post的传参方式

            string api = "";string sWo = "1025";          string url = "http://10.1.1.1/api/MES/API_GetLaserAOIParm";Dictionary<string, string> dics = new Dictionary<string, string>();dics = new Dictionary<string, string>{{ "sWo", sWo },            };Task<string> task = InvokeWebapi(url, api, "post", dics);string result = task.Result;

参考文献:WinForm如何调用WebApi接口_c# weiapi winform-CSDN博客

结语:本文主要记录WinFrom调用webapi接口方法及其应用实例,以上代码是本人亲测可用的,在此记录,方便查阅。

http://www.lryc.cn/news/413158.html

相关文章:

  • 智能巡检企业级域名 SSL 证书
  • 海思35XX系列(三)sensor(传感器)
  • dfs(续做)
  • OpenStack;异构算力网络架构;算力服务与交易技术;服务编排与调度技术
  • PLC-Recorder对于数据采集时间戳偏差的修正功能
  • 自定义监控
  • 关于使用php的mpdf插件遇到的一些问题
  • 电脑截图,颜色变淡的问题解决
  • uniApp跳转外链
  • 科技云报道:大模型引领技术浪潮,AI安全治理面临“大考”
  • SpringSecurity+Mysql数据库实现用户安全登录认证
  • 虚拟网卡添加ip
  • Unity向量线性插值Lerp
  • fatal: Could not read from remote repository. 解决方法
  • postman查询单条数据Get方法,无任何输出,idea后端也没有任何数据和提示的解决方法
  • query怎么改写,才能实现高质量的知识问答系统
  • Python实战——轻松实现动态网页爬虫(附详细源码)
  • Python应用—利用opencv实现图像匹配
  • Excel函数基础(二)
  • 学习大数据DAY30 python基础语法3
  • 一文弄清Java的四大引用及其两大传递
  • arduino程序-MC猜数字5、6(基础知识)
  • 【笔记】如何在ps里调整贴图
  • 【C++11】深度解析--异步操作(什么是异步?异步有那些操作?异步操作有什么用呢?)
  • PHP苹果 V X iPhone微商i o s多分开V X语音转发密友朋友圈一键跟圈软件
  • LDR6020 iPad皮套一体式键盘充电方案解析
  • 一款功能强大且免费的跨平台图片批量处理工具
  • 用Python打造精彩动画与视频,4.2 特效和滤镜的使用
  • 在 iOS 系统中,如何设置才能更好地保护个人隐私?
  • Charles抓包工具系列文章(七)-- Rewrite工具的应用示例