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

服务方法

 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         }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xinyuan178

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值