【问题标题】:C# - Google API request access_token - 400 - bad requestC# - Google API 请求 access_token - 400 - 错误请求
【发布时间】:2020-11-08 05:32:40
【问题描述】:

我正在尝试从 google (youtube) 获取 access_token,我按照文档进行操作,但响应是 400 - 错误请求。

            NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", _clientID);
            parameters.Add("client_secret", _clientSecret);
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", redirectUri);
            parameters.Add("code", Url.Encode(code));
            parameters.Add("content-type", "application/x-www-form-urlencoded");

            WebClient client = new WebClient();
            var result = client.UploadValues("https://accounts.google.com/o/oauth2/token", "POST", parameters);

在文档中我找到了网址: https://oauth2.googleapis.com/token 响应:System.Net.WebException:'远程服务器返回错误:(400)错误请求。'

我试过了: https://www.googleapis.com/oauth2/v4/token 响应:System.Net.WebException:'远程服务器返回错误:(400)错误请求。'

并且: https://accounts.google.com/o/oauth2/token 响应:System.Net.WebException:'远程服务器返回错误:(400)错误请求。'

您能帮忙解决这个问题吗?

提前致谢

【问题讨论】:

    标签: c# google-api http-post


    【解决方案1】:

    我必须将标头部分写入 WebClient 并且无需对“代码”进行编码

                NameValueCollection parameters = new NameValueCollection();
                parameters.Add("client_id", _clientID);
                parameters.Add("client_secret", _clientSecret);
                parameters.Add("grant_type", "authorization_code");
                parameters.Add("redirect_uri", redirectUri);
                parameters.Add("code", code);
    
                WebClient client = new WebClient();
                client.Headers.Add("content-type", "application/x-www-form-urlencoded");
                var result = client.UploadValues("https://oauth2.googleapis.com/token", "POST", parameters);
    

    像这样工作得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多