淘宝开发平台获取access_token(sessionkey)

C#代码:

 public HttpResponseMessage GetAccessToken(string code,string appkey, string appsecret)
        {
            WebUtils webUtils = new WebUtils();
            IDictionary<string, string> param = new Dictionary<string, string>();
            string url = "https://oauth.taobao.com/token";
            string responseMsg = "";
            try
            {
                param.Add("grant_type", "authorization_code");
                param.Add("code", code);
                param.Add("client_id", appkey);
                param.Add("client_secret", appsecret);
                param.Add("redirect_uri", "");
                param.Add("view", "web");
                string response = webUtils.DoPost(url, param,null);
                CacheManager.Put("AccessToken", response, new TimeSpan(1, 0, 0));
                responseMsg = "操作成功";
            }
            catch (Exception)
            {
                responseMsg = "操作失败";
            }

            return new HttpResponseMessage
            {
                Content = new StringContent(responseMsg, Encoding.UTF8, "application/xml")
            };
        }

post方法:
 public string DoPost(string url, IDictionary<string, string> textParams, IDictionary<string, string> headerParams)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", headerParams);
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(textParams));
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = GetResponseEncoding(rsp);
            return GetResponseAsString(rsp, encoding);
        }

 

 
posted @ 2018-04-08 16:09  CH随风而散  阅读(725)  评论(0编辑  收藏  举报