winform调用api接口post方法


 1 /// <summary>
 2         /// 调用WEBAPI方法
 3         /// </summary>
 4         /// <param name="url">地址</param>
 5         /// <param name="body">参数</param>
 6         /// <returns></returns>
 7         public static string HttpPost(string url, string body, string method = "POST")
 8         {
 9             try
10             {
11                 Encoding encoding = Encoding.UTF8;
12                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
13                 request.Method = method;
14                 request.Accept = "text/html, application/xhtml+xml, */*";
15                 request.ContentType = "application/json";
16 
17                 byte[] buffer = encoding.GetBytes(body);
18                 request.ContentLength = buffer.Length;
19                 if (method.Equals("POST"))
20                 {
21                     request.GetRequestStream().Write(buffer, 0, buffer.Length);
22                 }
23                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
24                 using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
25                 {
26                     return reader.ReadToEnd();
27                 }
28             }
29             catch (WebException ex)
30             {
31 
32                 HttpWebResponse response = (HttpWebResponse)ex.Response;
33                 if (response != null)
34                 {
35                     Console.WriteLine("Error code: {0}", response.StatusCode);
36 
37                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default))
38                     {
39                         string text = reader.ReadToEnd();
40 
41                         int start = text.IndexOf("System.Exception:");
42                         string s = text.Substring(start, 2000);
43                         throw new Exception("XX" + s);
44 
45 
46                     }
47                 }
48                 else
49                 {
50                     throw new Exception("XX" + ex.Message);
51                 }
52 
53             }
54         }

实体类

 

string str = HttpHelper.HttpPost(url,“”);

调用


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM