Created
March 31, 2023 14:15
-
-
Save JamesIgoe/867bb389aba2688f5199530c62c26630 to your computer and use it in GitHub Desktop.
Basics of generic method for making API calls
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
//using System.Net.Http | |
//using System.Net.Http.Headers | |
public async Task<T> GetInfoAsync<T>(string url, string apiKey, string referer) | |
{ | |
try | |
{ | |
using (HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true })) | |
{ | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-API-KEY", apiKey); | |
client.DefaultRequestHeaders.Add("Referer", referer); | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
var response = client.GetAsync(url).Result; | |
if (response.IsSuccessStatusCode) | |
{ | |
var responseContent = await response.Content.ReadAsStringAsync(); | |
var result = JsonConvert.DeserializeObject<T>(responseContent); | |
return result; | |
} | |
else | |
return (T)Activator.CreateInstance(typeof(T)); | |
} | |
} | |
catch (Exception ex) | |
{ | |
return (T)Activator.CreateInstance(typeof(T)); | |
} | |
} | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment