WinForm如何調用WebApi接口

本人接觸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獲取的結果如上圖所示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章