DamageAssessment_Backend/DamageAssesmentApi/DamageAssesment.Api.Responses/Services/HttpUtil.cs

43 lines
1.6 KiB
C#
Raw Permalink Normal View History

using DamageAssesment.Api.Responses.Interfaces;
using DamageAssesment.Api.Responses.Models;
using System.Net.Http.Headers;
using System.Text;
2023-10-04 17:45:51 -05:00
namespace DamageAssesment.Api.Responses.Services
{
public class HttpUtil : IHttpUtil
{
private readonly HttpClient httpClient;
private readonly ILogger<HttpUtil> logger;
public HttpUtil(HttpClient httpClient, ILogger<HttpUtil> logger)
{
this.httpClient = httpClient;
this.logger = logger;
}
public async Task<string> SendAsync(HttpMethod method, string url, string JsonInput, string token)
{
try
{
var request = new HttpRequestMessage(method, url);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (method == HttpMethod.Post)
{
request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json");
}
var response = await httpClient.SendAsync(request, CancellationToken.None);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
catch (Exception ex)
{
logger?.LogError($"Exception Message : {ex.Message} - Ref: HttpUtil.SendAsync()");
return null;
}
}
}
}