• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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

[csharp] view plain copy
  1.        /// <summary>  
  2.        /// 调用api返回json  
  3.        /// </summary>  
  4.        /// <param name="url">api地址</param>  
  5.        /// <param name="jsonstr">接收参数</param>  
  6.        /// <param name="type">类型</param>  
  7.        /// <returns></returns>  
  8.        public static string HttpApi(string url, string jsonstr, string type)  
  9.        {  
  10.            Encoding encoding = Encoding.UTF8;  
  11.            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址  
  12.            request.Accept = "text/html,application/xhtml+xml,*/*";  
  13.            request.ContentType = "application/json";  
  14.            request.Method = type.ToUpper().ToString();//get或者post  
  15.            byte[] buffer = encoding.GetBytes(jsonstr);  
  16.            request.ContentLength = buffer.Length;  
  17.            request.GetRequestStream().Write(buffer, 0, buffer.Length);  
  18.            HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
  19.            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))  
  20.            {  
  21.                return reader.ReadToEnd();  
  22.            }  
  23.        }  

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

[csharp] view plain copy
  1. private void button3_Click(object sender, EventArgs e)  
  2.         {  
  3.             string url = "...(此处为api端口)/api/VisitorInfo/GetEndVisitorInfoList";  
  4.             var str = ApiHelper.HttpApi(url, "{}""get");  
  5.         }  

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

HttpWebRequest请求时无法发送具有此谓词类型的内容正文。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl); //--需要封装的参数
            request.CookieContainer = new CookieContainer();
            CookieContainer cookie = request.CookieContainer;//如果用不到Cookie,删去即可 
            //以下是发送的http头

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
简化MVVM属性设置和修改-.NETCORE(C#)WPF开发发布时间:2022-07-10
下一篇:
C#之猴子吃桃儿问题的解法——猴子吐桃儿发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap