2

我正在尝试使用 c# 获取 Google APi 的 access_token,但总是收到错误消息 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

4

1 回答 1

3

尝试删除对HttpUtility.UrlEncode请求数据中每个项目的调用。您不需要这样做,因为数据不会进入它正在发布的 url。毫无疑问,这会稀释正在发送的信息,从而导致您的Invalid Request回复。

于 2012-08-08T12:02:42.153 回答