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

时间:2013-03-22 14:48:05

标签: c# .net dotnetopenauth google-oauth

我使用以下代码从代码中获取访问令牌,如下所示

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.

我不知道我哪里出错了

等待您的宝贵意见

1 个答案:

答案 0 :(得分:0)

Google还提供了一个更高级别的库来访问其服务。我发现它可以更容易地使用它的API。

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