Google Api获取令牌请求会返回invalid_request

时间:2012-08-08 11:54:56

标签: c# oauth-2.0 google-authentication

我正在尝试使用c#获取Google APis访问令牌,并始终收到错误消息invalid_request。有我的代码:

var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";

var RequestData = "";
foreach (var Item in Params)
{
    RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}

string Url = "https://accounts.google.com/o/oauth2/token";

var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";

var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
    request.ContentLength = SendData.Length;
    Stream OutputStream = request.GetRequestStream();
    OutputStream.Write(SendData, 0, SendData.Length);
} catch {}

try
{
    using (var response = (HttpWebResponse) request.GetResponse())
    {
        var stream = response.GetResponseStream();
        var sr = new StreamReader(stream);
        string JSON = sr.ReadToEnd();
    }
} catch {}

我使用https://developers.google.com/accounts/docs/OAuth2WebServer#offline

1 个答案:

答案 0 :(得分:3)

尝试删除请求数据中每个项目的HttpUtility.UrlEncode调用。您不应该这样做,因为数据不会进入它被POST的URL。毫无疑问,这会稀释正在发送的信息,从而导致您的Invalid Request响应。