谷歌 API OAuth 访问令牌检索 - 400 错误请求



我正在尝试检索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) 错误请求"。GetResponse() 行。我哪里出错了?

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

相关内容

  • 没有找到相关文章

最新更新