Repository URL to install this package:
Version:
1.3.1 ▾
|
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Fluctio.FluctioSim.Utils.Extensions
{
public static class HttpClientExtensions
{
private static async Task<HttpResponseMessage> MakeHttpRequest(this HttpClient client, HttpMethod method, string endpoint, string accessToken = null, CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(method, endpoint);
if (accessToken != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
return await client.SendAsync(request, cancellationToken);
}
public static async Task<string> MakeApiCallRaw(this HttpClient client, HttpMethod method, string endpoint, string accessToken = null, CancellationToken cancellationToken = default)
{
var response = await client.MakeHttpRequest(method, endpoint, accessToken, cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public static async Task<T> MakeApiCallJson<T>(this HttpClient client, HttpMethod method, string endpoint, string accessToken = null, CancellationToken cancellationToken = default)
{
var responseString = await client.MakeApiCallRaw(method, endpoint, accessToken, cancellationToken);
try
{
return JsonConvert.DeserializeObject<T>(responseString);
}
catch (JsonReaderException exception)
{
throw new HttpRequestException($"Wrong json string\n{responseString}", exception);
}
}
}
}