问题描述
我确实意识到,使用C#和其他语言检查网站是否存在不同的方法。但是,我已经了解到其中有些效果不佳。例如,这段代码:
WebClient client = new WebClient();
try
{
string response = client.DownloadString(url);
return true; // Successful -> the website does exist.
}
catch
{
return false; // Unsuccessful -> the website doesn't exist.
}
没有检测到www.bb.com,尽管该网站显然确实存在。在这里我绝对应该使用哪种代码绝对安全?
解决方法
鉴于:
- 您链接的网站希望在User-Agent字符串中设置一种主要浏览器
- 与WebClient相比,更推荐和更新HttpClient
您可以这样做:
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace resourcechecker
{
class Program
{
static HttpClient client = new HttpClient();
public async static Task<bool> ResourceExists(HttpClient client,string url)
{
HttpResponseMessage response;
response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
static void Main(string[] args)
{
client.DefaultRequestHeaders.Add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0");
string url = "http://www.bb.com/";
Console.WriteLine($"It is {ResourceExists(client,url).Result} that {url} exists");
}
}
}
但是,例如,如果测试计算机的IP地址被阻止访问该Web服务器,这仍然可能给出错误的答案