.net 或 Xamarin Internet 可用性检查当 WIFI 网络没有 Internet 连接时 [英] .net or Xamarin Internet availability check when the WIFI network has no internet connection
问题描述
我知道如何检查设备是否有可用的互联网连接是一个很大的讨论.
我尝试了 Ping、WebClient 和 HTTPClient.我还使用 Xamarin Essentials 和连接插件.
所有这些都在起作用,只需向谷歌或您选择的服务器发出请求,您就会得到答案与否.您还可以设置超时时间为 2 秒等.
但现在我遇到了这样的情况:我已连接到 WIFI,但 WIFI 本身没有活动的互联网连接.
所以我写的所有东西都不再起作用了.问题是超时将以某种方式被忽略.也许是 .net 中的错误?我不知道.
现在我发现了最后一件事:
试试{var request = (HttpWebRequest)WebRequest.Create("https://www.google.com");request.KeepAlive = false;request.Timeout = 2000;使用 (var response = (HttpWebResponse)await request.GetResponseAsync()){如果(响应.StatusCode == HttpStatusCode.OK){//连接到互联网可用返回真;}别的{//无法连接到互联网返回假;}}}捕获(WebException webEx){if (webEx.Status == WebExceptionStatus.Timeout){返回假;}}捕获(例外 e){返回假;}
这是我在达到 2 秒超时时收到 WebException 的唯一解决方案.在所有其他解决方案中,我坚持了超过 1 分钟,直到达到超时.同样,当我将其设置为 500 毫秒之类的时候.
有没有人知道为什么没有达到给定的超时时间,例如使用其他方法?
解决方案:
可以使用DependencyService
来实现,参考如下代码
在 Forms 中,创建一个界面
使用系统;命名空间 app1{公共接口 INetworkAvailable{bool IsNetworkAvailable();}}
<块引用>
在 iOS 项目中
使用系统;使用 Xamarin.Forms;使用基金会;[程序集:依赖(typeof(IsNetworkAvailableImplement))]命名空间 xxx.iOS{公共类 IsNetworkAvailableImplement:INetworkAvailable{公共 IsNetworkAvailableImplement(){}bool INetworkAvailable.IsNetworkAvailable(){NSString urlString = new NSString("http://captive.apple.com");NSUrl url = new NSUrl(urlString);NSUrlRequest request = new NSUrlRequest(url, NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 3);NSData data = NSUrlConnection.SendSynchronousRequest(request, out NSUrlResponse response, out NSError error);NSString 结果 = NSString.FromData(data,NSStringEncoding.UTF8);if(result.Contains(new NSString("Success"))){返回真;}别的{返回假;}}}}
不要忘记允许 HTTP 访问.在 info.plist 中添加以下代码
NSAppTransportSecurity <字典><key>NSAllowsArbitraryLoads</key><真/></dict>
<块引用>
在安卓项目中
使用系统;使用 Java.Lang;使用 Xamarin.Forms;[程序集:依赖(typeof(IsNetworkAvailableImplement))]命名空间 xxx.Droid{公共类 IsNetworkAvailableImplement:INetworkAvailable{公共 IsNetworkAvailableImplement(){}public bool IsNetworkAvailable(){运行时运行时 = Runtime.GetRuntime();Process process = runtime.Exec("ping -c 3 www.google.com");int 结果 = process.WaitFor();如果(结果== 0){返回真;}别的{返回假;}}}}
现在你可以在表单中调用它了,就像
bool isAvailable= DependencyService.Get().IsNetworkAvailable();如果(可用){Console.WriteLine("网络可用");}别的{Console.WriteLine("网络不可用");}
i know its a big discussion how to check if there is a internet connection available for the device.
I tried Ping, WebClient and HTTPClient. I also use Xamarin Essentials and the Connectivity Plugin.
All this things are working, just make a request to google or the server of your choice and you will get back the answer or not. You can also set a timeout for 2 seconds and so on.
But now i came to the situation where i'm connected to the WIFI BUT the WIFI itself has no active internet connection.
So all the things i wrote about was not working anymore. The problem is that the timeout will be ignored somehow. Maybe a bug in .net? I don't know.
Now i found one last thing:
try
{
var request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.KeepAlive = false;
request.Timeout = 2000;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//Connection to internet available
return true;
}
else
{
//Connection to internet not available
return false;
}
}
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.Timeout)
{
return false;
}
}
catch (Exception e)
{
return false;
}
This was the only solution where i got the WebException when the 2 seconds timeout was reached. In all other solutions i stuck more than 1 minute till the timeout was reached. Also when i set it to 500ms or something.
Did anybody know the reason why the given timeout is not reached for example with other methodes about?
Solution:
You can use DependencyService
to implement it .Refer the following code.
in Forms ,create an interface
using System;
namespace app1
{
public interface INetworkAvailable
{
bool IsNetworkAvailable();
}
}
in iOS project
using System;
using Xamarin.Forms;
using Foundation;
[assembly: Dependency(typeof(IsNetworkAvailableImplement))]
namespace xxx.iOS
{
public class IsNetworkAvailableImplement:INetworkAvailable
{
public IsNetworkAvailableImplement()
{
}
bool INetworkAvailable.IsNetworkAvailable()
{
NSString urlString = new NSString("http://captive.apple.com");
NSUrl url = new NSUrl(urlString);
NSUrlRequest request = new NSUrlRequest(url, NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 3);
NSData data = NSUrlConnection.SendSynchronousRequest(request, out NSUrlResponse response, out NSError error);
NSString result = NSString.FromData(data,NSStringEncoding.UTF8);
if(result.Contains(new NSString("Success")))
{
return true;
}
else
{
return false;
}
}
}
}
Don't forget to allow HTTP access .add the following code in info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
in Android project
using System;
using Java.Lang;
using Xamarin.Forms;
[assembly: Dependency(typeof(IsNetworkAvailableImplement))]
namespace xxx.Droid
{
public class IsNetworkAvailableImplement:INetworkAvailable
{
public IsNetworkAvailableImplement()
{
}
public bool IsNetworkAvailable()
{
Runtime runtime = Runtime.GetRuntime();
Process process = runtime.Exec("ping -c 3 www.google.com");
int result = process.WaitFor();
if(result==0)
{
return true;
}
else
{
return false;
}
}
}
}
Now you can call it in forms ,just like
bool isAvailable= DependencyService.Get<INetworkAvailable>().IsNetworkAvailable();
if(isAvailable)
{
Console.WriteLine("network is available");
}
else
{
Console.WriteLine("network is unavailable");
}
这篇关于.net 或 Xamarin Internet 可用性检查当 WIFI 网络没有 Internet 连接时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!