82 lines
2.7 KiB
C#
82 lines
2.7 KiB
C#
using System.Diagnostics;
|
|
using System.Text;
|
|
using Jugenddienst_Stunden.Types;
|
|
using System.Text.Json;
|
|
|
|
|
|
namespace Jugenddienst_Stunden.Models;
|
|
|
|
class Auth {
|
|
public static async Task<string> GetApiDataWithAuthAsync(string url, string token) {
|
|
// Erstellen eines HttpClient-Objekts
|
|
using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) {
|
|
|
|
client.DefaultRequestHeaders.Add("Accept", "application/json");
|
|
|
|
// Hinzufügen des Bearer-Tokens zum Authorization-Header
|
|
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
|
|
|
|
|
// Senden der Anfrage und Abrufen der Antwort
|
|
using (HttpResponseMessage HttpResponseMessage = await client.GetAsync(url).ConfigureAwait(false)) {
|
|
// Überprüfen, ob die Anfrage erfolgreich war
|
|
if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK) {
|
|
using (HttpContent HttpContent = HttpResponseMessage.Content) {
|
|
// Lesen und Rückgabe der Antwort als String
|
|
string responseData = await HttpContent.ReadAsStringAsync();
|
|
return responseData;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
public static async Task SaveItemAsync(string url, string token, DayTime item, bool isNewItem = false) {
|
|
//using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) {
|
|
|
|
try {
|
|
HttpClient client = new HttpClient();
|
|
client.DefaultRequestHeaders.Add("Accept", "application/json");
|
|
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
|
|
|
string json = JsonSerializer.Serialize<DayTime>(item);
|
|
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
|
|
HttpResponseMessage response = null;
|
|
if (isNewItem)
|
|
response = await client.PostAsync(url, content);
|
|
else
|
|
response = await client.PutAsync(url, content);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
Debug.WriteLine(@"\tTodoItem successfully saved.");
|
|
} catch (Exception ex) {
|
|
Debug.WriteLine(@"\tERROR {0}", ex.Message);
|
|
}
|
|
//}
|
|
}
|
|
|
|
public static async Task DeleteItemAsync(string url, string token) {
|
|
//using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(15) }) {
|
|
|
|
try {
|
|
HttpClient client = new HttpClient();
|
|
client.DefaultRequestHeaders.Add("Accept", "application/json");
|
|
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
|
|
|
HttpResponseMessage response = await client.DeleteAsync(url);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
Debug.WriteLine(@"\tTodoItem successfully deleted.");
|
|
} catch (Exception ex) {
|
|
Debug.WriteLine(@"\tERROR {0}", ex.Message);
|
|
}
|
|
//}
|
|
}
|
|
|
|
|
|
}
|