Tom
Tom

Reputation: 797

Google Api get token request returns invalid_request

I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:

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 {}

I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline

Upvotes: 3

Views: 1845

Answers (1)

James
James

Reputation: 82136

Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.

Upvotes: 3

Related Questions