【问题标题】:google api oauth access token retrieval - 400 bad requestgoogle api oauth 访问令牌检索 - 400 错误请求
【发布时间】:2012-11-06 19:58:54
【问题描述】:

我正在尝试检索 oauth 访问令牌以调用 asp.net mvc 中的某些 google api,并且我为一个操作编写了以下代码:

        public ActionResult GetOAuthToken()
        {

        String url = "https://accounts.google.com/o/oauth2/token";

        // Create a request using a URL that can receive a post. 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Host = "accounts.google.com";
        // Create POST data and convert it to a byte array.
        string postData = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"].ToString(), OAuthConfig.client_id, OAuthConfig.client_secret, OAuthConfig.token_redirect_uri);
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byteArray = encoding.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();

        // SOME CODE TO PROCESS THE RESPONSE

        Response.Redirect("/Home");
        return View();
        }

OAuthConfig 只是一个包含客户端 ID、客户端密码等的类。

我不断收到“远程服务器返回错误:(400) 错误请求。”在 request.GetResponse() 行。我哪里错了?

【问题讨论】:

  • 有响应正文吗?它说什么?
  • 没有。行 request.GetResponse() 抛出异常
  • 几乎可以肯定。捕获 WebException 并检查其属性。 msdn.microsoft.com/en-us/library/…
  • 我确实使用调试器检查了 WebException,但我没有发现任何有用的东西。您究竟在哪里找到响应正文?
  • catch(WebException ex){ var response = ex.Response; ...}?如果它不为空,则解码响应流。它可能包含更多信息。

标签: c# oauth google-api


【解决方案1】:

Google 确实提供了一个更高级别的库来处理其服务,它处理 url 的格式,我发现它使使用他们的 api 变得更加容易。见http://code.google.com/p/google-api-dotnet-client/

【讨论】:

  • 我尝试使用 .net 库,但如果您已经拥有授权码,则没有任何关于如何简单地获取访问令牌的明确教程。我也看到了此处发布的示例代码:code.google.com/p/google-api-dotnet-client/wiki/OAuth2,但它是在一个简单的客户端应用程序的上下文中。我不知道如何在我的场景中翻译代码,我在查询字符串中有授权代码。
猜你喜欢
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
相关资源
最近更新 更多