78 lines
2.0 KiB
C#
78 lines
2.0 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace PostmanCloneLibrary;
|
|
|
|
public class ApiAccess : IApiAccess
|
|
{
|
|
|
|
private readonly HttpClient _httpClient = new();
|
|
|
|
public async Task<string> CallApiAsync(
|
|
string url,
|
|
string content,
|
|
HttpAction action = HttpAction.GET,
|
|
bool formaOutput = true
|
|
)
|
|
{
|
|
StringContent stringContent = new(content, Encoding.UTF8, "application/json");
|
|
return await CallApiAsync(url, stringContent, action, formaOutput);
|
|
}
|
|
public async Task<string> CallApiAsync(
|
|
string url,
|
|
HttpContent? content = null,
|
|
HttpAction action = HttpAction.GET,
|
|
bool formaOutput = true
|
|
)
|
|
{
|
|
HttpResponseMessage response;
|
|
|
|
switch (action)
|
|
{
|
|
case HttpAction.GET:
|
|
response = await _httpClient.GetAsync(url);
|
|
break;
|
|
case HttpAction.POST:
|
|
response = await _httpClient.PostAsync(url, content);
|
|
break;
|
|
default:
|
|
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
|
|
|
}
|
|
|
|
|
|
//response = await _httpClient.GetAsync(url);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
string json = await response.Content.ReadAsStringAsync();
|
|
|
|
if (json != null && formaOutput)
|
|
{
|
|
var jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
|
|
json = JsonSerializer.Serialize(jsonElement,
|
|
new JsonSerializerOptions { WriteIndented = true });
|
|
}
|
|
|
|
return json;
|
|
}
|
|
else
|
|
{
|
|
return $"Error: {response.StatusCode}";
|
|
}
|
|
}
|
|
|
|
public bool IsValidUrl(string url)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(url))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
bool output = Uri.TryCreate(url, UriKind.Absolute, out Uri uriOutput) &&
|
|
(uriOutput.Scheme == Uri.UriSchemeHttps);
|
|
|
|
return output;
|
|
}
|
|
}
|