C/S系统也可以和B/S系统一样实现“前后端分离”,那这样写winform就相当于纯粹的前端页面了,然后再单独部署一个webapi项目,通过api调用数据库进行数据的操作,有利于维护和数据安全性的提高,那么winform怎么去调用api接口呢,写了一个demo,大家借鉴一下哈,本人才疏学浅,有不足和错误请指出:
winform界面就不设计了,仅仅是为了测试是否调用到api,直接在创建的类库中写一个方法:
-
-
-
-
-
-
-
- public static string HttpApi(string url, string jsonstr, string type)
- {
- Encoding encoding = Encoding.UTF8;
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Accept = "text/html,application/xhtml+xml,*/*";
- request.ContentType = "application/json";
- request.Method = type.ToUpper().ToString();
- 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接收数据格式如下:
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;
|
|
请发表评论