• 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 }
  • 相关阅读:
    CodeForces 450
    CodeForces 400
    CodeForces 1
    [HDU POJ] 逆序数
    [HDU 1166] 敌兵布阵
    [转] 树状数组学习
    关于1月4日到1月7日
    [HDU 1565+1569] 方格取数
    [POJ 1459] Power Network
    [转] 网络流算法--Ford-Fulkerson方法及其多种实现
  • 原文地址:https://www.cnblogs.com/miaoxiao/p/request_webapi_by_cs.html
Copyright © 2020-2023  润新知