QQ微博API使用记录

下载SDK 下载地址:  http://open.t.qq.com/download/C%23-SDK.7z ,不过下载这SDK在发送图片的时候有问题。稍候讲解。

1. Oauth 登录

    a. 获取request_token

        /// <summary>
        /// 获取request_token
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns>oauth_token=a63f4a0e1242462fb8c11e53159ba294&oauth_token_secret=40ece707e064128e4fec692e3c09c692&oauth_callback_confirmed=true</returns>
        private string GetRequestToken(string appKey, string appSecret)
        {
            string url = "https://open.t.qq.com/cgi-bin/request_token";
            List<Parameter> parameters = new List<Parameter>();
            OauthKey oauthKey = new OauthKey();
            oauthKey.customKey = appKey;
            oauthKey.customSecrect = appSecret;
            //特别注意,返回是在这里添加的。
            oauthKey.callbackUrl = "http://localhost:2377/tqq/AccessToken";

            QWeiboRequest request = new QWeiboRequest();

            string request_token = request.SyncRequest(url, "GET", oauthKey, parameters, null);
            //获取oauth_token_secret
            ParseToken(request_token);
            //把获取的oauth_token_secret保存在txt文件里(测试时用的,正式使用应该保存数据库比较好)
            string txtPath = Server.MapPath("~/tokenSecret.txt");
            if (System.IO.File.Exists(txtPath))
            {
                System.IO.File.Delete(txtPath);
            }
            using (System.IO.StreamWriter sw = System.IO.File.AppendText(Server.MapPath("~/tokenSecret.txt")))
            {
                sw.Write(tokenSecret);
            }
            //end
            return request_token;
        }

 b. 用户授权request_token

<a href="https://open.t.qq.com/cgi-bin/authorize?GetRequestToken">login</a>

   

上面authorize?后面的GetRequestToken即第一步返回的。

c. 交换access_token

是返回到 http://localhost:2377/tqq/AccessToken 这地址,即第一步填写的oauthKey.callbackUrl

        /// <summary>
        /// 交换access_token
        /// </summary>
        /// <returns></returns>
        public ActionResult AccessToken()
        {
            //获取返回的oauth_verifier
            OauthVerify = Request.Params["oauth_verifier"] ?? "";
            //获取oauth_token
            tokenKey = Request.Params["oauth_token"] ?? "";

            //获取第一步保存的tokenSecret
            tokenSecret = System.IO.File.OpenText(Server.MapPath("~/tokenSecret.txt")).ReadToEnd();
            //去交换
            string AccessToken = GetAccessToken(CustomKey, CustomSecret, tokenKey, tokenSecret, OauthVerify);
            //交换成功后返回到/tqq/auth 获取需要的oauth_token与oauth_token_secret
            return Redirect("/tqq/auth?" + AccessToken);
        }

        /// <summary>
        /// 交换access_token
        /// </summary>
        /// <param name="customKey"></param>
        /// <param name="customSecret"></param>
        /// <param name="requestToken"></param>
        /// <param name="requestTokenSecrect"></param>
        /// <param name="verify"></param>
        /// <returns></returns>
        private string GetAccessToken(string customKey, string customSecret, string requestToken, string requestTokenSecrect, string verify)
        {
            string url = "https://open.t.qq.com/cgi-bin/access_token";
            List<Parameter> parameters = new List<Parameter>();
            OauthKey oauthKey = new OauthKey();
            oauthKey.customKey = customKey;
            oauthKey.customSecrect = customSecret;
            oauthKey.tokenKey = requestToken;
            oauthKey.tokenSecrect = requestTokenSecrect;
            oauthKey.verify = verify;

            QWeiboRequest request = new QWeiboRequest();
            return request.SyncRequest(url, "GET", oauthKey, parameters, null);
        }

d. 成功获取需要的oauth_token与oauth_token_secret开始使用吧。

        public ActionResult Auth()
        {
            //在这里要把返回的oauth_token与oauth_token_secret保存下来以方便下次直接调用其他API
            string oauth_token = Request.Params["oauth_token"];
            string tokenSecrect = Request.Params["oauth_token_secret"];

            //以下是测试发布一条微博
            string url = "http://open.t.qq.com/api/t/add";

            List<Parameter> parameters = new List<Parameter>();
            OauthKey oauthKey = new OauthKey();
            oauthKey.customKey = CustomKey;
            oauthKey.customSecrect = CustomSecret;
            
            oauthKey.tokenKey = oauth_token;
            oauthKey.tokenSecrect = tokenSecrect;

            //注意这些参数一定要小写,文档里有些大写的copy过来也要小写哦
            parameters.Add(new Parameter("format", HttpUtil.GetUtfParameters("json")));
            parameters.Add(new Parameter("content", HttpUtil.GetUtfParameters("test api ok?"+ DateTime.Now.ToString())));
            parameters.Add(new Parameter("clientip", HttpUtil.GetUtfParameters("127.0.0.1")));

            List<Parameter> files = new List<Parameter>();
            QWeiboRequest request = new QWeiboRequest();
            string result = request.SyncRequest(url, "GET", oauthKey, parameters, files);
            
            ViewBag.Info = result;
            return View();
        }

        /// <summary>
        /// value进行utf8编码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetUtfParameters(string value)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(value);
            return utf8.GetString(encodedBytes);
        }

其他:

        public const string CustomKey = "-------------------------------";
        public const string CustomSecret = "------------------------------";

        private string OauthVerify = null;
        private string tokenKey = null;
        private string tokenSecret = null;

为什么添加发布带图片的微博不成功?

修改SyncHttp.cs 大约在128行的

string formitem = string.Format(formdataTemplate, param.Name, param.Value);

修改成

string formitem = string.Format(formdataTemplate, param.Name, FormParamDecode(param.Value));
FormParamDecode是AsyncHttp.cs里面的。添加好了就可以了。

private string FormParamDecode(string value)//转换%XX
        {
            int nCount = 0;
            for (int i = 0; i < value.Length; i++)//计算数组大小
            {
                if (value[i] == '%')
                {
                    i += 2;
                }
                nCount++;
            }

            byte[] sb = new byte[nCount];

            for (int i = 0, index = 0; i < value.Length; i++)
            {
                if (value[i] != '%')
                {
                    sb.SetValue((byte)value[i], index++);
                }
                else
                {
                    StringBuilder sChar = new StringBuilder();
                    sChar.Append(value[i + 1]);
                    sChar.Append(value[i + 2]);
                    sb.SetValue(Convert.ToByte(sChar.ToString(), 16), index++);
                    i += 2;
                }
            }
            UTF8Encoding utf8 = new UTF8Encoding();
            return utf8.GetString(sb);
        }

posted on 2011-06-10 10:21  myx  阅读(1325)  评论(0编辑  收藏  举报