【发布时间】:2017-12-14 02:40:48
【问题描述】:
我正在使用以下方法来检查一个 URL 是否存在或是否有效。
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
private static Boolean CheckURL(string url)
{
using (MyClient myclient = new MyClient())
{
try
{
myclient.HeadOnly = true;
// fine, no content downloaded
string s1 = myclient.DownloadString(url);
return true;
}
catch (Exception error)
{
return false;
}
}
}
我的方法正确吗?如何向用户显示已检查 URL 的状态,例如:404、成功等?
请指教..
【问题讨论】:
-
您需要查看 WebException 暴露的状态码:Web Response status code可能重复
-
你可能还应该包含一个可信的用户代理标题。
-
@AlexK。您介意将其添加为答案吗..
-
您可以自己关闭此问题作为副本。
标签: c# .net network-programming system.web