I am working on a Android Xamarin App. This app connects to a device through Wi-fi (the device is a Access Point) and while the app is connected to the device, there's no internet connection on the phone.
So when I disconnect from the device AP and connect the phone to another network with internet connection, I try to make HTTP requests to the server and I always get "Network is Unreachable" error, even tho the phone does have connection (tested accessing Chrome). Only works again after I restart the app.
I am using all the good practices I found online regarding HttpClient class (not wrapped in a "using" statement, using only one static HttpClient object instead of creating a new one on each request, etc.)
I implemented IHttpClientFactory to create the HttpClient, but still gets the same error.
My code (simplified):
public static class WebRepository
{
private static IHttpClientFactory _clientFactory;
private static HttpClient _client;
static WebRepository()
{
_clientFactory = Startup.ServiceProvider.GetService<IHttpClientFactory>();
_client = _clientFactory.CreateClient();
}
public static async Task<T> GetAsync<T>(string url)
{
try
{
if (Globals.LoggedUser != null)
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", $"{Globals.LoggedUser.Token}");
HttpResponseMessage message = await _client.GetAsync(url).ConfigureAwait(false);
return await DeserializeResponseMessageAsync<T>(message);
}
catch(HttpRequestException e) when(e.InnerException != null && e.InnerException is SocketException && e.Message.Contains("Network is unreachable"))
{
_client.CancelPendingRequests();
_client.Dispose();
_client = _clientFactory.CreateClient(); //Tried to create a new client in order to "refresh" connection, so in the next Get request it would be a new client, but no luck. Still gets the excepction every time.
throw e;
}
catch(Exception) { throw; }
}
}