Last active
October 31, 2018 08:17
-
-
Save andy51002000/449d56352ae5b592a4fddf4bfd8d0754 to your computer and use it in GitHub Desktop.
Make Http request to FB to get access token
This file contains 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
public static async Task<string> GetFacebookProfileName(string accessToken) | |
{ | |
var uri = GetUri("https://graph.facebook.com/v2.6/me", | |
Tuple.Create("fields", "id,name"), | |
Tuple.Create("access_token", accessToken)); | |
var res = await FacebookRequest<FacebookProfile>(uri); | |
return res.Name; | |
} | |
private static async Task<T> FacebookRequest<T>(Uri uri) | |
{ | |
string json; | |
using (HttpClient client = new HttpClient()) | |
{ | |
json = await client.GetStringAsync(uri).ConfigureAwait(false); | |
} | |
try | |
{ | |
var result = JsonConvert.DeserializeObject<T>(json); | |
return result; | |
} | |
catch (JsonException ex) | |
{ | |
throw new ArgumentException("Unable to deserialize the Facebook response.", ex); | |
} | |
} | |
private static Uri GetUri(string endPoint, params Tuple<string, string>[] queryParams) | |
{ | |
var queryString = HttpUtility.ParseQueryString(string.Empty); | |
foreach (var queryparam in queryParams) | |
{ | |
queryString[queryparam.Item1] = queryparam.Item2; | |
} | |
var builder = new UriBuilder(endPoint); | |
builder.Query = queryString.ToString(); | |
return builder.Uri; | |
} | |
//if not support HttpUtility.ParseQueryString, below is an alternative way | |
//https://stackoverflow.com/questions/27442985/alternative-to-httputility-parsequerystring-without-system-web-dependency | |
//public static Uri GetUri(string endPoint, params Tuple<string, string>[] queryParams) | |
//{ | |
// var builder = new UriBuilder(endPoint); | |
// string paramUrl = string.Join("&", queryParams.Select(u => $"{WebUtility.UrlEncode(u.Item1)}={WebUtility.UrlEncode(u.Item2)}")); | |
// builder.Query = paramUrl; | |
// return builder.Uri; | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment