码迷,mamicode.com
首页 > Windows程序 > 详细

c# Winfom客户端 POST访问WebApi 方法

时间:2020-03-30 23:38:08      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:bytes   coding   end   cat   login   post   姓名   客户   type   

服务方法

 1 [AllowAnonymousAttribute]
 2         [HttpPost]
 3         public string PostWebName(dynamic login)
 4         {
 5             Dictionary<string, string> dict = new Dictionary<string, string>();
 6             dict.Add("姓名", Convert.ToString(login.name));
 7             dict.Add("密码", Convert.ToString(login.pwd));
 8 
 9             return Tools.ConvertToJsonStr(dict);
10 
11         }

客户端调用方法

1 Dictionary<string, string> dic = new Dictionary<string, string>();
2             dic.Add("name", "第一个参数");
3             dic.Add("pwd", "第二个参数");
4 
5             string url = "http://localhost:10450/api/EmpInfo/PostWebName";
6 
7             textBox2.Text = HttpPost(url, ObjectToJson(dic));

 

 1  string HttpPost(string URL, string Para)
 2         {
 3             // 创建HttpWebRequest对象
 4             HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(URL);
 5             httpRequest.Method = "POST";
 6            httpRequest.ContentType = "application/json";
 7             httpRequest.Headers.Add("Authorization", "lzsin");
 8 
 9             byte[] bytes = Encoding.UTF8.GetBytes(Para);
10             using (Stream reqStream = httpRequest.GetRequestStream())
11             {
12                 reqStream.Write(bytes, 0, bytes.Length);
13                 reqStream.Flush();
14             }
15             try
16             {
17                 using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
18                 {
19                     StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
20                     string responseString = sr.ReadToEnd();
21                     return responseString;
22                 }
23             }
24             catch (WebException ex)
25             {
26                 var res = (HttpWebResponse)ex.Response;
27                 StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
28                 string str = sr.ReadToEnd();
29                 return str;
30             }
31         }

 

c# Winfom客户端 POST访问WebApi 方法

标签:bytes   coding   end   cat   login   post   姓名   客户   type   

原文地址:https://www.cnblogs.com/lzsin/p/12601738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!