예제 #1
0
        /// <summary>
        ///更新票据
        /// </summary>
        /// <param name="forced">true:强制更新.false:按缓存是否到期来更新</param>
        public static void UpdateAccessToken(bool forced = false)
        {
            //ConstVars.CACHE_TIME是缓存时间(常量,也可放到配置文件中),这样在有效期内则直接从缓存中获取票据,不需要再向服务器中获取。
            if (!forced && AccessToken.Begin.AddSeconds(ConstVars.CACHE_TIME) >= DateTime.Now)
            {//没有强制更新,并且没有超过缓存时间
                return;
            }

            string CorpID     = ConfigHelper.FetchCorpID();
            string CorpSecret = ConfigHelper.FetchCorpSecret();
            string TokenUrl   = Urls.gettoken;
            String apiurl     = $"{TokenUrl}?{Keys.corpid}={CorpID}&{Keys.corpsecret}={CorpSecret}";

            WebRequest request = WebRequest.Create(apiurl);

            request.Method = "GET";
            WebResponse  response   = request.GetResponse();
            Stream       stream     = response.GetResponseStream();
            Encoding     encode     = Encoding.UTF8;
            StreamReader reader     = new StreamReader(stream, encode);
            string       resultJson = reader.ReadToEnd();

            TokenResult tokenResult = JsonConvert.DeserializeObject <TokenResult>(resultJson);

            if (tokenResult.ErrCode == ErrCodeEnum.OK)
            {
                AccessToken.Value = tokenResult.Access_token;
                AccessToken.Begin = DateTime.Now;
            }
            else
            {
                ResultPackage xx = new ResultPackage();
                xx.ErrMsg = tokenResult.ErrMsg;
            }
        }
예제 #2
0
        /// <summary>
        /// 分析结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resultJson"></param>
        /// <returns></returns>
        private static T AnalyzeResult <T>(string resultJson) where T : ResultPackage, new()
        {
            ResultPackage tempResult = null;

            if (!String.IsNullOrEmpty(resultJson))
            {
                tempResult = JsonConvert.DeserializeObject <ResultPackage>(resultJson);
            }
            T result = null;

            if (tempResult != null && tempResult.IsOK())
            {
                result = JsonConvert.DeserializeObject <T>(resultJson);
            }
            else if (tempResult != null)
            {
                result = tempResult as T;
            }
            else if (tempResult == null)
            {
                result = new T();
            }
            result.Json = resultJson;
            return(result);
        }