Last active
October 19, 2015 07:54
-
-
Save LindaLawton/7349e2f8e84152dede07 to your computer and use it in GitHub Desktop.
takes a refreshtoken and exchanges it for an accessotken.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AccessTokenResponse | |
{ | |
public string access_token { get; set; } | |
public string token_type { get; set; } | |
public string expires_in { get; set; } | |
} | |
/// <summary> | |
/// takes a refreshtoken and exchanges it for an accessotken. | |
/// </summary> | |
/// <param name="refreshToken"></param> | |
/// <returns></returns> | |
public static string getAcccessToken(string refreshToken) | |
{ | |
string url = "https://accounts.google.com/o/oauth2/token"; | |
string postData = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token", Properties.Resources.clientId, Properties.Resources.secret, refreshToken); | |
// Create a request using a URL that can receive a post. | |
WebRequest request = WebRequest.Create(url); | |
// Set the Method property of the request to POST. | |
request.Method = "POST"; | |
byte[] byteArray = Encoding.UTF8.GetBytes(postData); | |
// Set the ContentType property of the WebRequest. | |
request.ContentType = "application/x-www-form-urlencoded"; | |
// Set the ContentLength property of the WebRequest. | |
request.ContentLength = byteArray.Length; | |
// Get the request stream. | |
Stream dataStream = request.GetRequestStream(); | |
// Write the data to the request stream. | |
dataStream.Write(byteArray, 0, byteArray.Length); | |
// Close the Stream object. | |
dataStream.Close(); | |
// Get the response. | |
WebResponse response = request.GetResponse(); | |
// Display the status. | |
Console.WriteLine(((HttpWebResponse)response).StatusDescription); | |
// Get the stream containing content returned by the server. | |
dataStream = response.GetResponseStream(); | |
// Open the stream using a StreamReader for easy access. | |
StreamReader reader = new StreamReader(dataStream); | |
// Read the content. | |
string responseFromServer = reader.ReadToEnd(); | |
AccessTokenResponse tmp = JsonConvert.DeserializeObject<AccessTokenResponse>(responseFromServer); | |
// Display the content. | |
Console.WriteLine(responseFromServer); | |
// Clean up the streams. | |
reader.Close(); | |
dataStream.Close(); | |
response.Close(); | |
return tmp.access_token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment