尝试使用C#从Google检索令牌的错误请求

时间:2013-01-13 00:36:16

标签: c# oauth

我正在尝试复制此处详述的流程; https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse

在C#中

        String authorizationCode = String.Empty;
        String consumerKey       = String.Empty;
        String consumerSecret    = String.Empty;
        String redirectUrl       = String.Empty;
        String grantType         = String.Empty;
        String requestContent = String.Empty;
        HttpWebRequest request = null;
        byte[] byteArray = null;
        Stream dataStream = null;
        WebResponse response = null;
        StreamReader reader = null;
        String serverResponse = String.Empty;

        byte[] authorizationResult = null;

        try
        {
            authorizationCode = HttpUtility.UrlEncode(context.Request.QueryString["code"]);
            consumerKey       = Properties.Settings.Default.GoogleConsumerKey;
            consumerSecret    = Properties.Settings.Default.GoogleConsumerSecret;
            redirectUrl       = Properties.Settings.Default.RedirectUrl;
            grantType = "authorization_code";

            request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            request.Method = "POST";

            requestContent = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_url={3}&grant_type={4}",authorizationCode,consumerKey,consumerSecret,redirectUrl,grantType);
            byteArray = Encoding.UTF8.GetBytes(requestContent);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            response = request.GetResponse();
            dataStream = response.GetResponseStream();

            reader = new StreamReader(dataStream);
            serverResponse = HttpUtility.UrlDecode(reader.ReadToEnd());

            reader.Close();
            dataStream.Close();
            response.Close();



        }
        catch (System.Exception ex)
        {
            throw ex;
        }
        finally
        {

        }

麻烦就是在调用GetResponse()时我收到了错误的请求。

ConsumerKey&秘密是我在注册申请时从谷歌那里得到的。 authorizationCode也来自Google。

任何想法我做错了什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我有同样的问题: “using”关键字为我解决了这个问题。点击链接:

https://stackoverflow.com/a/1968543/1820776