zoukankan      html  css  js  c++  java
  • 构建API

    前言

    过程,如图:

    第一步创建一个帮助类,类里面提供了加密、组装Url等方法,代码如下:

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Web;
      5 using System.IO;
      6 using System.Net;
      7 using System.Security.Cryptography;
      8 using System.Text; 
      9 
     10 namespace APIClient.Content
     11 {
     12     public class WebHelper
     13     {
     14 
     15         #region 获得客户端时间+ public static int GetTimeZ(DateTime time)
     16         public static int GetTimeZ(DateTime time)
     17         {
     18             var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
     19             return (int)(time - startTime).TotalSeconds;
     20         }
     21         #endregion
     22 
     23         #region 加密key+private string CreateSign(Dictionary<string, string> paramList, string appKey)
     24         public static string CreateSign(Dictionary<string, string> paramList, string appKey)
     25         {
     26             var str = paramList.OrderBy(c => c.Key).Aggregate(string.Empty, (current, item) => current + item.Value);
     27             return MD5(str + appKey).ToLower();//调用MD5
     28         }
     29         #endregion
     30 
     31         #region 执行HTTP GET请求+ public static string DoGet(string url, IDictionary<string, string> parameters)
     32         public static string DoGet(string url, IDictionary<string, string> parameters)
     33         {
     34             if (parameters != null && parameters.Count > 0)
     35             {
     36                 if (url.Contains("?"))
     37                 {
     38                     url = url + "&" + BuildPostDate(parameters); //调用BuildPostDate
     39                 }
     40                 else
     41                 {
     42                     url = url + "?" + BuildPostDate(parameters);
     43                 }
     44             }
     45 
     46             HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
     47             req.Method = "GET";
     48             req.KeepAlive = true;
     49             req.UserAgent = "ADCSDK";
     50             req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
     51             HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
     52             Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
     53             return GetResponseAsString(rsp, encoding); //调用GetResponseAsString
     54         }
     55 
     56         #endregion
     57 
     58         #region MD5加密+ public static string MD5(string input)
     59         /// <summary>
     60         /// MD5加密 (添加命名空间;using System.Security.Cryptography;)
     61         /// </summary>
     62         /// <param name="input">输入字符串</param>
     63         /// <returns>加密后的字符串</returns>
     64         public static string MD5(string input)
     65         {
     66             if (string.IsNullOrEmpty(input))
     67             {
     68                 return string.Empty;
     69             }
     70 
     71             var md5 = new MD5CryptoServiceProvider();
     72             var inputBytes = Encoding.UTF8.GetBytes(input);
     73             var outPutbytes = md5.ComputeHash(inputBytes);
     74             return BitConverter.ToString(outPutbytes).Replace("-", "");
     75         }
     76         #endregion
     77 
     78         #region 组装普通文本请求参数+ private static string BuildPostDate(IDictionary<string, string> parameters)
     79         private static string BuildPostDate(IDictionary<string, string> parameters)
     80         {
     81             StringBuilder postDate = new StringBuilder();
     82             bool hasParam = false;
     83             IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
     84             while (dem.MoveNext())
     85             {
     86                 string name = dem.Current.Key;
     87                 string value = dem.Current.Value;
     88                 if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
     89                 {
     90                     if (hasParam)
     91                     {
     92                         postDate.Append("&");
     93                     }
     94                     postDate.Append(name);
     95                     postDate.Append("=");
     96                     postDate.Append(Uri.EscapeDataString(value));
     97                     hasParam = true;
     98                 }
     99             }
    100             return postDate.ToString();
    101         }
    102         #endregion
    103 
    104         #region 把响应流转换为文本+ private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    105         private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    106         {
    107             StringBuilder result = new StringBuilder();
    108             Stream stream = null;
    109             StreamReader reader = null;
    110 
    111             try
    112             {
    113                 stream = rsp.GetResponseStream();
    114                 reader = new StreamReader(stream, encoding);
    115                 var buffer = new char[256];
    116                 int readBytes;
    117                 while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
    118                 {
    119                     result.Append(buffer, 0, readBytes);
    120                 }
    121             }
    122             finally
    123             {
    124                 if (reader != null) reader.Close();
    125                 if (stream != null) stream.Close();
    126                 if (rsp != null) rsp.Close();
    127             }
    128             return result.ToString();
    129         }
    130         #endregion
    131 
    132 
    133     }
    134 }
    View Code

    第二步服务器端创建一个API(参数协商定义),代码如下:

     1  public ActionResult Reg(int productId, string version, string source, string userName, string timeZ, string sign)
     2         {
     3             if (string.IsNullOrEmpty(version))
     4                 return Content("productId");
     5             if (string.IsNullOrEmpty(version))
     6                 return Content("version");
     7             if (string.IsNullOrEmpty(version))
     8                 return Content("source");
     9             if (string.IsNullOrEmpty(version))
    10                 return Content("userName");
    11             if (string.IsNullOrEmpty(version))
    12                 return Content("timeZ");
    13             if (string.IsNullOrEmpty(version))
    14                 return Content("sign1");
    15 
    16             var dict = new Dictionary<string, string>
    17                            {
    18                                {"productId", productId.ToString()},
    19                                {"version", version},
    20                                {"source", source},
    21                                {"userName", userName},
    22                                {"timeZ", timeZ},
    23                            };
    24 
    25             var checkSign =WebHelper.CreateSign(dict, "zz680000f7-6834");//sign 是数据库中一个key,这里是为了方便,应当是根据productId值从数据库中取出相应的key与程序传过来的key比较
    26                 
    27             if (sign.ToLower() != checkSign.ToLower())
    28             {
    29                 return Content("sign2");
    30             }
    31             //调用接口之后还应当在数据库中插入一条日志数据
    32             return Content("1");
    33         } 
    View Code

    第三步应用程序创建一个方法,请求API,代码如下:

     1  public ActionResult List()
     2         {
     3             RegTest();
     4             return View();
     5         }
     6         //参数
     7         private const string APIUrl = "http://localhost:4023/APISever/";
     8         private const int ProductId = 3;
     9         private const string AppKey = "zz680000f7-68341";//680000f7-6834-4b5f-8534-70cea7fd641b
    10 
    11         //注册接口
    12         public void RegTest()
    13         {
    14             var url = string.Format("{0}reg", APIUrl);
    15             var dict = new Dictionary<string, string>
    16                            {
    17                                 {"productId", ProductId.ToString()},
    18                                {"version", "1.0.0.1"},
    19                                {"source", "lg"},
    20                                {"userName", "zlzl"},
    21                                {"timeZ",WebHelper.GetTimeZ(DateTime.Now).ToString()},//调用GetTimeZ
    22                            };
    23 
    24             dict["sign"] =WebHelper.CreateSign(dict, AppKey);//调用CreateSign
    25 
    26             var result = WebHelper.DoGet(url, dict);//调用DoGet
    27             Response.Write(string.Format("注册接口测试结果:{0}",result));
    28         }
    View Code
  • 相关阅读:
    机器人学——1.6-双向量表示法
    机器人学——1.5-奇异点及万向节锁
    机器人学——1.4-三角度表示法
    机器人学——1.3-正交旋转矩阵
    MySQL数据库操作
    ArrayList和LinkedList的区别
    redis 常用命令
    idea快捷键
    Spring
    JDBC
  • 原文地址:https://www.cnblogs.com/zl879211310/p/3486040.html
Copyright © 2011-2022 走看看