c# - google api oauth 访问 token 检索 - 400 错误请求

标签 c# oauth google-api

我正在尝试检索 oauth 访问 token 以调用 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() 行。我哪里错了?

最佳答案

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

关于c# - google api oauth 访问 token 检索 - 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13444613/

相关文章:

android - 我可以查询 Google Play Developer API 的剩余配额吗?

c# - Android Oreo 中无法访问 Google Smart Lock 保存对话框

c# - Dijkstra 的算法问题

iphone - Facebook iOS SDK : Login to Facebook without always ask for permissions for the application

c# - 如何在 C# 中拆分字符串?

php - Twitter OAuth + 自动登录 + MYSQL

ios - 无效签名 : oauth_signature

ios - 找到 `Firebase/Auth` 依赖项,但它们需要更高的最低部署目标

c# - 有没有办法在更新数据库期间显示输出?

c# - 查找具有元组项的最小累积和的列表