WinForm如何调用WebApi接口

  • Post author:
  • Post category:其他



本人接触B/S项目偏多,但是由于近期需要写到小工具,首选肯定是WinForm哇。顺手把笔记记录下来,有需要的盆友的可以参考下:

首先得写一个WinFrom调用webapi接口的通用方法(PS:一般情况下是post或者get,特殊情况下会用到复杂结构input),这里以get为例,直接上代码:

       #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

然后写个方法直接调用WebApi获取结果解析之后绑定到对应的DataGridView即可,直接上代码:

     #region 获取APP升级版本信息
        public List<Versions> GetVersList()
        {
            string api = "";
            List<Versions> list = new List<Versions>();
            string url = "http://域名/api/Config/GetVersionList?ClientType=android";
            Dictionary<string, string> dics = new Dictionary<string, string>();
            Task<string> task = InvokeWebapi(url, api, "GET", dics);
            string result = task.Result;
            #region 解析结果集
            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 == 1)
                {
                    JArray jlist = JArray.Parse(jsonObj["data"].ToString());
                    for (int i = 0; i < jlist.Count; ++i)  //遍历JArray  
                    {
                        Versions ver = new Versions();
                        JObject tempo = JObject.Parse(jlist[i].ToString());
                        ver.VersionId = Convert.ToInt32(tempo["versionId"]);
                        ver.VersionNumber = tempo["versionNumber"].ToString();
                        ver.Description = tempo["description"].ToString();
                        ver.FilePath = tempo["filePath"].ToString();
                        ver.ClientType = tempo["clientType"].ToString();
                        ver.IsForce = Convert.ToInt32(tempo["isForce"]);
                        list.Add(ver);
                    }
                }
            }
            #endregion
            return list;
        }

        #endregion

绑定到DataGridView就不必多说啦,WebApi获取的结果如上图所示



版权声明:本文为XiaoRungen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。