从代码中获得访问令牌从谷歌oauth

本文关键字:谷歌 oauth 访问令牌 代码 | 更新日期: 2023-09-27 18:05:24

我使用下面的代码从下面的代码中获取访问令牌

String code = HttpContext.Current.Request["code"];
                    string redirecturl = HttpContext.Current.Request["url"];                                  
                    string Url = "https://accounts.google.com/o/oauth2/token";
                    string grant_type = "authorization_code";
                    string redirect_uri_encode = UrlEncodeForGoogle(url);
                    string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
                    HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
                    string result = null;
                    request.Method = "POST";
                    request.KeepAlive = true;
                    request.ContentType = "application/x-www-form-urlencoded";
                    string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
                    var bs = Encoding.UTF8.GetBytes(param);
                    using (Stream reqStream = request.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                    }
                    using (WebResponse response = request.GetResponse())
                    {
                        var sr = new StreamReader(response.GetResponseStream());
                        result = sr.ReadToEnd();
                        sr.Close();
                    }

我得到响应

 The remote server returned an error: (400) Bad Request.

我不知道哪里出错了

等待您的宝贵意见

从代码中获得访问令牌从谷歌oauth

Google还提供了一个更高级的库来访问其服务。我发现使用它的api要容易得多。

http://code.google.com/p/google-api-dotnet-client/