为什么这个WebRequest的,以sony.com抛出一个异常?抛出、异常、WebRequest、sony

2023-09-06 11:00:12 作者:屌丝同桌欢乐多

我的目标是写一个C#方法,如果一个URL指向了验证一个有效的在线资源。目前,它看起来是这样的:

My goal is to write a C# method that validates if a url points to a valid online resource. It currently looks something like this:

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);
}

这code抛出一个异常,即使我可以浏览到索尼的URL在Web浏览器。起初我还以为自己的Web服务器不支持HEAD。不知道是否有些不?但它仍然抛出一个异常,GET。任何建议如何更好地写code来处理这样的情况下?

This code throws an exception, even though I can browse to the sony url in a web browser. At first I thought their web server didn't support HEAD. Not sure if some don't? But it still throws an exception with GET. Any suggestions how to better write this code to handle cases such as this?

推荐答案

本网站需要用户代理头。加入这一行:

This site requires User-Agent header. Add this line:

request.UserAgent = "SO/1.0";