谷歌 API OAuth 访问令牌获取 - 400 错误请求

4

我正在尝试检索oauth访问令牌以便在asp.net mvc中调用某些谷歌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、客户端密钥等信息的类。

在请求的GetResponse()行,我一直收到“远程服务器返回错误:(400)错误请求。”。我错在哪里了?


有响应体吗?它说了什么? - spender
没有,代码会在请求 request.GetResponse() 这一行抛出异常。 - Nirav Bhatia
几乎肯定会有异常。捕获WebException并检查其属性。http://msdn.microsoft.com/en-us/library/system.net.webexception.response.aspx - spender
捕获(WebException ex){ var response = ex响应; ...}?如果它非空,请解码响应流。它可能包含更多信息。 - spender
一个400 - Bad Request的原因是数据格式不正确。你的请求出了问题。检查一下你的POST值是否有无效字符。 - Simon Whitehead
显示剩余3条评论
1个回答

1

1
我尝试使用 .net 库,但是没有明确的教程可以简单地获取访问令牌,如果您已经拥有授权码。我在这里看到了发布的示例代码:http://code.google.com/p/google-api-dotnet-client/wiki/OAuth2,但它是在一个简单客户端应用程序的上下文中。我不知道如何将代码转换到我的场景中,在我的场景中,我在查询字符串中拥有授权码。 - Nirav Bhatia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接