Google Calendar API - Bad Request (400) Trying To Swap Code For Access Token

大兔子大兔子 提交于 2019-11-29 18:00:58

Do you need the new lines \r\n in the body? This code works for me...

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
"2xxx61.apps.googleusercontent.com", "XJxxxFy",
"http://localhost:1599/home/oauth2callback"); //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);
        }
    }
}
}
catch (WebException wex){ var x = wex; }
catch (Exception ex){var x = ex;}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!