Working Get -reading from api
This commit is contained in:
47
PostmanCloneLibrary/ApiAccess.cs
Normal file
47
PostmanCloneLibrary/ApiAccess.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
namespace PostmanCloneLibrary
|
||||
{
|
||||
public class Class1
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
8
PostmanCloneLibrary/Enums.cs
Normal file
8
PostmanCloneLibrary/Enums.cs
Normal file
@ -0,0 +1,8 @@
|
||||
|
||||
|
||||
namespace PostmanCloneLibrary;
|
||||
|
||||
public enum HttpAction
|
||||
{
|
||||
GET
|
||||
}
|
||||
9
PostmanCloneLibrary/IApiAccess.cs
Normal file
9
PostmanCloneLibrary/IApiAccess.cs
Normal file
@ -0,0 +1,9 @@
|
||||
|
||||
namespace PostmanCloneLibrary
|
||||
{
|
||||
public interface IApiAccess
|
||||
{
|
||||
Task<string> CallApiAsync(string url, bool formaOutput, HttpAction action);
|
||||
bool IsValidUrl(string url);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user