Hello,
For this problem, you can use the Connectivity interface provided by Maui to make a connection judgment before calling the HTTP interface.
Please refer to the following code and documentation:
private async void Submit()
{
if(Connectivity.Current.NetworkAccess == NetworkAccess.Internet) // If the network is Internet state, then proceed with the following code
{
var jsonContent = new StringContent(JsonConvert.SerializeObject(new
{
bodyField1 = ""
}), Encoding.UTF8, "application/json");
connected = "N";
using (var client1 = new HttpClient())
{
string authurl = "https://myquizapi.azurewebsites.net/api/";
client1.BaseAddress = new Uri(authurl);
client1.DefaultRequestHeaders.Clear();
client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client1.PostAsync("Auth", jsonContent);
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
string json = await Res.Content.ReadAsStringAsync();
// Parse the JSON response to extract the address
dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jwttoken = data1.token;
}
}
string apiUrl = "https://myquizapi.azurewebsites.net/api/";
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwttoken}");
HttpResponseMessage response = null;
response = await client.GetAsync("pins");
// Check if the request was successful (status code 200)
if (response.IsSuccessStatusCode)
{
// Make a GET request to the API
connected = "Y";
// Read the content of the response
string jsonString = await response.Content.ReadAsStringAsync();
// Deserialize the JSON string into an object
Questions = JsonConvert.DeserializeObject<List<Questionpin>>(jsonString);
}
else { Questions = list1; }
}
}
catch (Exception ex)
{
if (connected == "N")
{
Questions = list1;
}
}
var result = Questions.FirstOrDefault(c => c.Pinnum == pin);
if (result == null)
{
errmsg = "Enter Valid pin";
}
else
{ Navigation.NavigateTo("/NewNav", true); }
}
else
{
Console.WriteLine("No Internet");
}
}
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.