httpclient

Hopefully no more AppCrash, when Server does not respond.
This commit is contained in:
2024-08-21 20:14:47 +02:00
parent 423e5f3cd2
commit 34f34c6242

View File

@@ -4,37 +4,56 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ZXing.QrCode.Internal; using ZXing.QrCode.Internal;
namespace Jugenddienst_Stunden.Models namespace Jugenddienst_Stunden.Models {
{
class Auth class Auth {
{
public Hours hours; public Hours hours;
public static async Task<string> GetApiDataWithAuthAsync(string url, string token) { public static async Task<string> GetApiDataWithAuthAsync(string url, string token) {
using (HttpClient client = new HttpClient()) {
try { try {
// Erstellen eines HttpClient-Objekts
using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) }) {
try {
client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Accept", "application/json");
// Hinzufügen des Bearer-Tokens zum Authorization-Header // Hinzufügen des Bearer-Tokens zum Authorization-Header
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); 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
using (HttpResponseMessage HttpResponseMessage = await client.GetAsync(url).ConfigureAwait(false)) {
if (HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK) {
using (HttpContent HttpContent = HttpResponseMessage.Content) {
string responseData = await HttpContent.ReadAsStringAsync();
return responseData;
}
}
}
// Senden der Anfrage und Abrufen der Antwort // Senden der Anfrage und Abrufen der Antwort
HttpResponseMessage response = await client.GetAsync(url); //HttpResponseMessage response = await client.GetAsync(url);
// Überprüfen, ob die Anfrage erfolgreich war // Überprüfen, ob die Anfrage erfolgreich war
response.EnsureSuccessStatusCode(); //response.EnsureSuccessStatusCode();
// Lesen und Rückgabe der Antwort als String // Lesen und Rückgabe der Antwort als String
string responseData = await response.Content.ReadAsStringAsync(); //string responseData = await response.Content.ReadAsStringAsync();
return responseData; //return responseData;
} catch (HttpRequestException e) { } catch (HttpRequestException e) {
// Fehlerbehandlung // Fehlerbehandlung
Console.WriteLine($"An error occurred: {e.Message}"); Console.WriteLine($"An error occurred: {e.Message}");
return null; return null;
} }
} }
} catch (Exception e) {
Console.WriteLine(e.Message);
return null;
}
return null;
} }
public static async Task Main(string[] args) { public static async Task Main(string[] args) {