Working Get -reading from api

This commit is contained in:
2024-05-09 14:50:25 +02:00
parent b584174707
commit 541ec847c3
7 changed files with 211 additions and 13 deletions

View File

@ -0,0 +1,47 @@
using System.Text.Json;
namespace PostmanCloneLibrary;
public class ApiAccess : IApiAccess
{
private readonly HttpClient _httpClient = new();
public async Task<string> CallApiAsync(
string url,
bool formaOutput = true,
HttpAction action = HttpAction.GET
)
{
var 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;
}
}