C#后端代码访问webapi
方法实现:
1 public static string PostMoths(string url, object obj_model, Dictionary<string, string> dic = null) 2 { 3 string param = JsonConvert.SerializeObject(obj_model); 4 System.Net.HttpWebRequest request; 5 request = (System.Net.HttpWebRequest)WebRequest.Create(url); 6 request.Method = "POST"; 7 request.ContentType = "application/json;charset=UTF-8"; 8 if (dic != null && dic.Count != 0) 9 { 10 foreach (var item in dic) 11 { 12 request.Headers.Add(item.Key, item.Value); 13 } 14 } 15 byte[] payload; 16 payload = System.Text.Encoding.UTF8.GetBytes(param); 17 request.ContentLength = payload.Length; 18 string strValue = ""; 19 try 20 { 21 Stream writer = request.GetRequestStream(); 22 writer.Write(payload, 0, payload.Length); 23 writer.Close(); 24 System.Net.HttpWebResponse response; 25 response = (System.Net.HttpWebResponse)request.GetResponse(); 26 System.IO.Stream s; 27 s = response.GetResponseStream(); 28 string StrDate = ""; 29 StreamReader Reader = new StreamReader(s, Encoding.UTF8); 30 while ((StrDate = Reader.ReadLine()) != null) 31 { 32 strValue += StrDate; 33 } 34 } 35 catch (Exception e) 36 { 37 strValue = e.Message; 38 } 39 return strValue; 40 }
调用代码:
1 Dictionary<string, string> headerDic = new Dictionary<string, string>(); 2 headerDic.Add("version", "1.0"); 3 string a = PostMoths("https://domain.com/api/Token/GetToken", new { str = "***" }, headerDic); 4 Result r = JsonConvert.DeserializeObject<Result>(a); 5 if (r.code > 0) 6 { 7 // todu 8 }