PWAPP/PWAPPv2/Source/API/APIConnection.cs
2023-08-14 17:10:38 -04:00

92 lines
2.9 KiB
C#

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace PWAPPv2.Source.API
{
public class APIConnection
{
private static string BaseURL;
public DataObjects.APICredentials Credentials;
private static bool ResponseReady = false;
private static string Response = "";
public APIConnection(string baseUrl, DataObjects.APICredentials credentials)
{
Credentials = credentials;
BaseURL = baseUrl;
}
public string GetResponse()
{
while (!ResponseReady) ;
return Response;
}
public static async void APIGet(string Call)
{
//WebRequest request = WebRequest.Create(BaseURL + Call);
//request.Method = "GET";
//request.ContentType = "application/json; charset=utf-8";
//var response = (HttpWebResponse)request.GetResponse();
//string text;
//using (var sr = new StreamReader(response.GetResponseStream()))
//{
// text = sr.ReadToEnd();
//}
//return text;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(Call);
}
}
public string SendPostRequestAsync(string apiUri)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseURL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
StringContent contetnt = new StringContent(Credentials.ToJsonString(), Encoding.UTF8, "application/json");
var response = client.PostAsync(apiUri, contetnt).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return "";
}
public string SendPostRequestAsync(string apiUri, string PostData)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseURL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
StringContent contetnt = new StringContent(PostData, Encoding.UTF8, "application/json");
var response = client.PostAsync(apiUri, contetnt).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return "";
}
}
}