我的目标是编写一个C#方法,验证url是否指向有效的在线资源。它目前看起来像这样:
string url = "http://www.sony.com/";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
var msg = response.StatusCode == HttpStatusCode.OK ? "OK" : "Dead Link";
Console.WriteLine(msg);
}
此代码抛出异常,即使我可以在Web浏览器中浏览sony url。起初我以为他们的网络服务器不支持HEAD。不确定是否有人不知道?但它仍然引发了GET的异常。有任何建议如何更好地编写此代码来处理此类案例?
答案 0 :(得分:3)
此网站需要User-Agent
标题。添加以下行:
request.UserAgent = "SO/1.0";