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

1.WinFrom调用webapi接口方法

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

cs 复制代码
 #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格式的数据从文件中读取出来。调用代码如下:

cs 复制代码
 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();

cs 复制代码
 public class DataInfo
    {
        public int statusCode { get; set; }
        public string message { get; set; }     
    }

Standard类

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

cs 复制代码
  public class Standard
    {
        public string line { get; set; }
        public string linePlace { get; set; }     
    }

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

using Newtonsoft.Json;

Standard.json文件

cs 复制代码
{
    "line": "B10",
    "linePlace": "CQ_1", 
 }

补充:

get的传参方式

cs 复制代码
            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的传参方式

cs 复制代码
            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接口方法及其应用实例,以上代码是本人亲测可用的,在此记录,方便查阅。

相关推荐
未来之窗软件服务4 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther4 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间5 小时前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec6 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
Tiger_shl6 小时前
【层面一】C#语言基础和核心语法-02(反射/委托/事件)
开发语言·c#
mudtools10 小时前
.NET驾驭Word之力:COM组件二次开发全攻略之连接Word与创建你的第一个自动化文档
后端·c#
王维志11 小时前
LiteDB详解
数据库·后端·mongodb·sqlite·c#·json·database
程序猿多布12 小时前
XLua教程之热补丁技术
unity·c#·lua·xlua
咕白m62513 小时前
C# Excel 读取入门教程:免费实现方法
c#·.net
相与还14 小时前
godot+c#使用godot-sqlite连接数据库
数据库·c#·godot