C#如何检查URL是否存在/有效?

我在Visual C#2005中做了一个简单的程序,它在Yahoo!上查找股票代码。 财务,下载历史数据,然后绘制指定股票代码的价格历史logging。

我知道我需要获取数据的确切URL,如果用户input一个现有的股票代码(或至less有一个与雅虎财经数据),它工作得很好。 但是,如果用户编制一个股票代码,则会出现运行时错误,因为程序试图从不存在的网页中提取数据。

我正在使用WebClient类,并使用DownloadString函数。 我浏览了WebClient类的所有其他成员函数,但没有看到任何可用于testingURL的内容。

我该怎么做?

您可以发出“HEAD”请求而不是“GET”?

(编辑) – 哈哈! 看起来我以前做过 ! 改为维基,以避免指责重新获得。 所以要testing一个URL而不需要下载内容的代价:

// using MyClient from linked post using(var client = new MyClient()) { client.HeadOnly = true; // fine, no content downloaded string s1 = client.DownloadString("http://google.com"); // throws 404 string s2 = client.DownloadString("http://google.com/silly"); } 

你会try / catch DownloadString来检查错误; 没有错误? 它存在…


用C#2.0(VS2005):

 private bool headOnly; public bool HeadOnly { get {return headOnly;} set {headOnly = value;} } 

 using(WebClient client = new MyClient()) { // code as before } 

这是这个解决scheme的另一个实现:

 using System.Net; /// /// Checks the file exists or not. /// /// The URL of the remote file. /// True : If the file exits, False if file not exists private bool RemoteFileExists(string url) { try { //Creating the HttpWebRequest HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //Setting the Request method HEAD, you can also use GET too. request.Method = "HEAD"; //Getting the Web Response. HttpWebResponse response = request.GetResponse() as HttpWebResponse; //Returns TRUE if the Status code == 200 response.Close(); return (response.StatusCode == HttpStatusCode.OK); } catch { //Any exception will returns false. return false; } } 

From: http : //www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/

这些解决scheme是相当不错的,但他们忘记了可能有其他的状态代码比200 OK。 这是我在生产环境中用于状态监控等的解决scheme。

如果在目标页面上存在urlredirect或其他条件,则使用此方法返回true。 此外,GetResponse()会抛出一个exception,因此你不会得到一个StatusCode。 您需要捕获exception并检查ProtocolError。

任何400或500状态码将返回false。 所有其他人返回true。 此代码很容易修改,以满足您对特定状态代码的需求。

 /// <summary> /// This method will check a url to see that it does not return server or protocol errors /// </summary> /// <param name="url">The path to check</param> /// <returns></returns> public bool UrlIsValid(string url) { try { HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load request.Method = "HEAD"; //Get only the header information -- no need to download any content HttpWebResponse response = request.GetResponse() as HttpWebResponse; int statusCode = (int)response.StatusCode; if (statusCode >= 100 && statusCode < 400) //Good requests { return true; } else if (statusCode >= 500 && statusCode <= 510) //Server Errors { log.Warn(String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url)); return false; } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors { return false; } else { log.Warn(String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url), ex); } } catch (Exception ex) { log.Error(String.Format("Could not test url {0}.", url), ex); } return false; } 

如果我正确理解你的问题,你可以使用这样一个小的方法给你的URLtesting的结果:

 WebRequest webRequest = WebRequest.Create(url); WebResponse webResponse; try { webResponse = webRequest.GetResponse(); } catch //If exception thrown then couldn't get response from address { return 0; } return 1; 

你可以把上面的代码包装在一个方法中,并用它来执行validation。 我希望这回答你所问的问题。

这是另一种select

 public static bool UrlIsValid(string url) { bool br = false; try { IPHostEntry ipHost = Dns.Resolve(url); br = true; } catch (SocketException se) { br = false; } return br; } 

这个解决scheme似乎很容易遵循:

 public static bool isValidURL(string url) { WebRequest webRequest = WebRequest.Create(url); WebResponse webResponse; try { webResponse = webRequest.GetResponse(); } catch //If exception thrown then couldn't get response from address { return false ; } return true ; } 

试试这个(确保你使用System.Net):

 public bool checkWebsite(string URL) { try { WebClient wc = new WebClient(); string HTMLSource = wc.DownloadString(URL); return true; } catch (Exception) { return false; } } 

当checkWebsite()函数被调用时,它会尝试获取传递给它的URL的源代码。 如果获得源代码,则返回true。 如果不是,则返回false。

代码示例:

 //The checkWebsite command will return true: bool websiteExists = this.checkWebsite("https://www.google.com"); //The checkWebsite command will return false: bool websiteExists = this.checkWebsite("https://www.thisisnotarealwebsite.com/fakepage.html"); 

Web服务器响应HTTP状态代码,指示请求的结果,例如200(有时202)意味着成功,404 – 没有find(见这里 )。 假设URL的服务器地址部分是正确的,你没有得到一个套接字超时,这个exception很可能告诉你HTTP状态代码是200以外的。我build议检查exception的类,看看exception是否携带HTTP状态码。

IIRC – 有问题的调用抛出WebException或后代。 检查class级名称以查看哪一个,并将该呼叫包装在一个try块中以捕获该条件。

我有一个更简单的方法来确定一个url是有效的天气。

 if (Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute)) { //... } 

接下来从已经给出的例子中,我会说,最好的做法是在这样的使用中包装响应

  public bool IsValidUrl(string url) { try { var request = WebRequest.Create(url); request.Timeout = 5000; request.Method = "HEAD"; using (var response = (HttpWebResponse)request.GetResponse()) { response.Close(); return response.StatusCode == HttpStatusCode.OK; } } catch (Exception exception) { return false; } }