When I run this code to call the Google API, all I get is a ‘Bad Request’ error, but I don’t know where I’m going wrong.
The code is being returned no problem from the authorization page on Google, it’s when the code gets to the part below that it fails. Please could someone tell me where I’m going wrong here?
I’m aware that there are libraries for this, but I’m trying to understand how to do this the RESTful way as a learning exercise.
Thanks
var code = Request.QueryString["code"];
var accessToken = string.Empty;
var req0 = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
req0.Method = "POST";
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri= {3}&grant_type=authorization_code",
code, //the code i got back
"xxxx.apps.googleusercontent.com",
"xxx",
Url.Encode("http://localhost/home/callback")
); //my return URI
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req0.ContentType = "application/x-www-form-urlencoded";
req0.ContentLength = byteArray.Length;
using (Stream dataStream = req0.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
try
{
using (WebResponse response = req0.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
string responseFromServer = reader.ReadToEnd();
var ser = new JavaScriptSerializer();
accessToken = ser.DeserializeObject(responseFromServer).ToString();
}
}
}
}
catch (WebException wex)
{
Debug.WriteLine(wex.ToString());
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
The Google API is very finicky when it comes to what you have entered into the API Console for your client id return URI, and what you enter in your code to call it.
I was missing the trailing forward slash. That was all. Lesson learnt…
Thanks to Jon and Sandeep for help point me in the right direction by comparing what was in the network traffic, and what I should have been sending.