0

我正在尝试复制此处详述的过程;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 & Secret 是我在注册应用程序时从 Google 获得的。授权码也来自谷歌。

任何想法我做错了什么?

提前致谢。

4

1 回答 1

0

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

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

于 2014-01-12T11:53:54.213 回答