你好我试图用用户输入的URL启动一个带有webview的意图,我一直在网上看到,我找不到具体的答案,如何在允许用户之前确保网站真正连接继续下一个活动。我发现了许多工具来确保URL遵循正确的格式,但实际上没有任何工具确保它可以实际连接。
答案 0 :(得分:2)
您可以使用WebClient
并检查是否抛出任何异常:
using (var client = new HeadOnlyClient())
{
try
{
client.DownloadString("http://google.com");
}
catch (Exception ex)
{
// URL is not accessible.
}
}
您可以捕获更具体的例外以使其更优雅。
您还可以使用WebClient的自定义修改来检查HEAD并减少下载的数据量:
class HeadOnlyClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
req.Method = "HEAD";
return req;
}
}
答案 1 :(得分:0)
我建议您使用 HttpHead 来处理AndroidHttpClient的简单请求,但现在已弃用。您可以尝试通过套接字实现HEAD请求。
答案 2 :(得分:0)
您可以先尝试ping该地址。
答案 3 :(得分:0)
另一种选择: Connectivity Plugin for Xamarin and Windows
Task<bool> IsReachable(string host, int msTimeout = 5000);
但是,任何成功的预检都不能保证,因为下一个请求可能会失败,所以你仍然应该处理它。
答案 4 :(得分:0)
以下是我最终要检查主机名是否可访问的内容。我正在连接到具有自签名证书的站点,这就是我在ServiceCertificateValidationCallback中拥有该委托的原因。
private async Task<bool> CheckHostConnectionAsync (string serverName)
{
string Message = string.Empty;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serverName);
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true;
};
// Set the credentials to the current user account
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "GET";
request.Timeout = 1000 * 40;
try
{
using (HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync ())
{
// Do nothing; we're only testing to see if we can get the response
}
}
catch (WebException ex)
{
Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
return false;
}
if (Message.Length == 0)
{
goToMainActivity (serverName);
}
return true;
}