using System; using System.Diagnostics; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Jugenddienst_Stunden.Types; using System.Text.Json; using ZXing.QrCode.Internal; namespace Jugenddienst_Stunden.Models { class Auth { public static async Task 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); //Beim Debugging im Lokalen Netz mit meinem Smartphone kommt es hier zu //system.net.webexception nachricht = socket closed //Grund: Falscher DNS-Server liefert falsche Server-IP // 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(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); } //} } } }