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

前端 未结 1 1790
情书的邮戳
情书的邮戳 2020-12-22 06:03

Having got an authorisation code from Google for accessing a user\'s calendar, I\'m now trying to swap this for an access token. According to their own docs:

相关标签:
1条回答
  • 2020-12-22 06:36

    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;}
    
    0 讨论(0)
提交回复
热议问题