快捷搜索: 王者荣耀 脱发

关于C# winform怎么调用webapi来获取到json数据

C/S系统也可以和B/S系统一样实现“前后端分离”,那这样写winform就相当于纯粹的前端页面了,然后再单独部署一个webapi项目,通过api调用数据库进行数据的操作,有利于维护和数据安全性的提高,那么winform怎么去调用api接口呢,写了一个demo,大家借鉴一下哈,本人才疏学浅,有不足和错误请指出:

winform界面就不设计了,仅仅是为了测试是否调用到api,直接在创建的类库中写一个方法:

      /// <summary>
       /// 调用api返回json
       /// </summary>
       /// <param name="url">api地址</param>
       /// <param name="jsonstr">接收参数</param>
       /// <param name="type">类型</param>
       /// <returns></returns>
       public static string HttpApi(string url, string jsonstr, string type)
       {
           Encoding encoding = Encoding.UTF8;
           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
           request.Accept = "text/html,application/xhtml+xml,*/*";
           request.ContentType = "application/json";
           request.Method = type.ToUpper().ToString();//get或者post
           byte[] buffer = encoding.GetBytes(jsonstr);
           request.ContentLength = buffer.Length;
           request.GetRequestStream().Write(buffer, 0, buffer.Length);
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
           using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
           {
               return reader.ReadToEnd();
           }
       }

然后再winform界面的事件中调用该方法:

private void button3_Click(object sender, EventArgs e)
        {
            string url = "...(此处为api端口)/api/VisitorInfo/GetEndVisitorInfoList";
            var str = ApiHelper.HttpApi(url, "{}", "get");
        }

本地运行后变量str接收数据格式如下:

经验分享 程序员 微信小程序 职场和发展