萤石云定时更新 accessToken

时间:2021-07-12
本文章向大家介绍萤石云定时更新 accessToken,主要包括萤石云定时更新 accessToken使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 class UpdateVideoTokenHelper
    {
        private static Timer myTimer;
        private static string appKey = ConfigurationManager.AppSettings["appKey"];
        private static string appSecret = ConfigurationManager.AppSettings["appSecret"];
        public static void SetTimer()
        {
            myTimer = new Timer(10000);
            myTimer.Elapsed += OnTimedEvent;
            myTimer.AutoReset = true;
            myTimer.Enabled = true;
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            long updateTime = UpdateToken();
            Timer timer = source as Timer;
            if (updateTime > 0)
            {
                timer.Interval = updateTime;
            }
            else
            {
                timer.Interval = 432000;
            }

        }
        private static long UpdateToken()
        {
            try
            {
                WebClient webClient = new WebClient();
                string postString = "appKey=" + appKey + "&appSecret=" + appSecret;
                //以form表单的形式上传
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                // 转化成二进制数组
                byte[] postData = Encoding.ASCII.GetBytes(postString);
                // 上传数据
                byte[] responseData = webClient.UploadData("https://open.ys7.com/api/lapp/token/get", "POST", postData);
                string res = Encoding.UTF8.GetString(responseData);
                var jsonObj = JObject.Parse(JsonConvert.DeserializeObject(res).ToString());
                if (jsonObj["code"].ToString() == "200")
                {
                    string accessToken = jsonObj["data"]["accessToken"].ToString();

                    string sql = "update FM_DEVICE  set EXTENDCODE5 = '" + accessToken + "'";
                    int excuteRes = DBHelper.ExecuteCommand(sql);
                
                }
          //计算出需要更新的时间 修改timer 执行时间
long expireTime = long.Parse(jsonObj["data"]["expireTime"].ToString()); DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0)); long nowTime = (DateTime.Now.Ticks - startTime.Ticks) / 10000; return expireTime - nowTime; } catch (Exception e) { Console.WriteLine(e.ToString()); return 20000; } } }

原文地址:https://www.cnblogs.com/xiaoqiyaozou/p/15003383.html