Пример #1
0
        /// <summary>
        /// 获取授权Token
        /// </summary>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="parameters"></param>
        /// <param name="responseData"></param>
        /// <returns></returns>
        private bool GetOAuthToken(string requestUrl, Parameters parameters, out NameValueCollection responseData)
        {
            this.LastError = null;
            responseData = null;
            parameters.Add("oauth_consumer_key", this.AppKey);
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_timestamp", Util.GenerateTimestamp());
            parameters.Add("oauth_nonce", Util.GenerateRndNonce());
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_signature", this.GenerateSignature("GET", requestUrl, parameters));
            string url = string.Concat(requestUrl, "?", parameters.BuildQueryString(true));

            SyncHttpRequest request = new SyncHttpRequest(url, this.Charset);
            try
            {
                string response = request.Get();
                if (!string.IsNullOrEmpty(response))
                {
                    responseData = HttpUtility.ParseQueryString(response, this.Charset);
                    this.Token = responseData["oauth_token"];
                    this.TokenSecret = responseData["oauth_token_secret"];
                    return !string.IsNullOrEmpty(this.Token) && !string.IsNullOrEmpty(this.TokenSecret);
                }
            }
            catch (Exception ex)
            {
                this.LastError = ex;
            }
            return false;
        }
Пример #2
0
        /// <summary>
        /// 对数据进行签名
        /// </summary>
        /// <param name="requestMethod">请求方法.如GET或POST</param>
        /// <param name="requestUrl">API请求地址</param>
        /// <param name="parameters">提交参数</param>
        /// <returns></returns>
        public string GenerateSignature(string requestMethod, string requestUrl, Parameters parameters)
        {
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", Util.UrlEncode(this.AppSecret), Util.UrlEncode(this.TokenSecret)));

            StringBuilder data = new StringBuilder(100);
            data.AppendFormat("{0}&{1}&", requestMethod.ToUpper(), Util.UrlEncode(requestUrl));
            //处理参数
            if (parameters != null)
            {
                parameters.Sort();
                data.Append(Util.UrlEncode(parameters.BuildQueryString(true)));
            }

            byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data.ToString());
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);

            return Convert.ToBase64String(hashBytes);
        }