C# 如何检查 URL 是否存在/有效?
我正在使用 Visual C# 2005 编写一个简单的程序,用于在 Yahoo! 上查找股票代码。 金融,下载历史数据,然后绘制指定股票代码的价格历史记录。
我知道获取数据所需的确切 URL,并且如果用户输入现有的股票代码(或至少包含雅虎财经上的数据),则它可以正常工作。 但是,如果用户编写了一个股票代码,那么我会遇到运行时错误,因为程序尝试从不存在的网页中提取数据。
我正在使用 WebClient 类,并使用 DownloadString 函数。 我查看了 WebClient 类的所有其他成员函数,但没有看到任何可以用来测试 URL 的内容。
我怎样才能做到这一点?
I am making a simple program in visual c# 2005 that looks up a stock symbol on Yahoo! Finance, downloads the historical data, and then plots the price history for the specified ticker symbol.
I know the exact URL that I need to acquire the data, and if the user inputs an existing ticker symbol (or at least one with data on Yahoo! Finance) it works perfectly fine. However, I have a run-time error if the user makes up a ticker symbol, as the program tries to pull data from a non-existent web page.
I am using the WebClient class, and using the DownloadString function. I looked through all the other member functions of the WebClient class, but didn't see anything I could use to test a URL.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
这是此解决方案的另一个实现:
来自: http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/
Here is another implementation of this solution:
From: http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/
您可以发出 "HEAD" 请求,而不是 "得到”?
因此,要测试 URL 而无需下载内容:
您可以在
DownloadString
周围try
/catch
来检查错误; 没有错误? 它存在...使用 C# 2.0 (VS2005):
和
You could issue a "HEAD" request rather than a "GET"?
So to test a URL without the cost of downloading the content:
You would
try
/catch
around theDownloadString
to check for errors; no error? It exists...With C# 2.0 (VS2005):
and
这些解决方案非常好,但他们忘记了除了 200 OK 之外还可能有其他状态代码。 这是我在生产环境中用于状态监控等的解决方案。
如果目标页面上存在 url 重定向或其他条件,则使用此方法返回 true。 此外,GetResponse() 将引发异常,因此您将无法获得它的 StatusCode。 您需要捕获异常并检查 ProtocolError。
任何 400 或 500 状态代码都将返回 false。 其他所有都返回 true。
可以轻松修改此代码以满足您对特定状态代码的需求。
These solutions are pretty good, but they are forgetting that there may be other status codes than 200 OK. This is a solution that I've used on production environments for status monitoring and such.
If there is a url redirect or some other condition on the target page, the return will be true using this method. Also, GetResponse() will throw an exception and hence you will not get a StatusCode for it. You need to trap the exception and check for a ProtocolError.
Any 400 or 500 status code will return false. All others return true.
This code is easily modified to suit your needs for specific status codes.
很多答案都比 HttpClient 更旧(我认为它是在 Visual Studio 2013 中引入的)或者没有异步/等待功能,所以我决定发布我自己的解决方案:
我使用
HttpClient.SendAsync
和 < code>HttpMethod.Head 仅发出 head 请求,而不下载整个文件。 就像 David 和 Marc 已经说过的那样,不仅有 http 200 就可以了,所以我使用IsSuccessStatusCode
来允许所有成功状态代码。A lot of the answers are older than HttpClient (I think it was introduced in Visual Studio 2013) or without async/await functionality, so I decided to post my own solution:
I use
HttpClient.SendAsync
withHttpMethod.Head
to make only a head request, and not downlaod the whole file. Like David and Marc already say there is not only http 200 for ok, so I useIsSuccessStatusCode
to allow all Sucess Status codes.如果我正确理解你的问题,你可以使用这样的小方法来给你 URL 测试的结果:
你可以将上面的代码包装在一个方法中并使用它来执行验证。 我希望这能回答您所问的问题。
If I understand your question correctly, you could use a small method like this to give you the results of your URL test:
You could wrap the above code in a method and use it to perform validation. I hope this answers the question you were asking.
我一直发现异常的处理速度要慢得多。
也许强度较低的方法会产生更好、更快的结果?
然后只需使用:
I have always found Exceptions are much slower to be handled.
Perhaps a less intensive way would yeild a better, faster, result?
Then just use:
试试这个(确保您使用 System.Net):
当调用 checkWebsite() 函数时,它会尝试获取以下内容的源代码
传入其中的 URL。 如果获取到源代码,则返回 true。 如果不,
它返回 false。
代码示例:
Try this (Make sure you use System.Net):
When the checkWebsite() function gets called, it tries to get the source code of
the URL passed into it. If it gets the source code, it returns true. If not,
it returns false.
Code Example:
这个解决方案似乎很容易遵循:
This solution seems easy to follow:
这是另一个选择
Here is another option
许多其他答案都在使用 WebRequest,但它现在已经过时了。
这是一个具有最少代码并使用当前最新的类和方法的方法。
我还测试了其他投票最多的函数,这些函数可能会产生误报。
我使用这些 URL 进行了测试,这些 URL 指向 Visual Studio 社区安装程序 在此页面找到。
请注意,这不适用于 .NET Framework,因为 HttpClient.Send 不存在。
要使其在 .NET Framework 上运行,您需要将
client.Send(request)
更改为client.SendAsync(request).Result
。A lot of other answers are using WebRequest which is now obsolete.
Here is a method that has minimal code and uses currently up-to-date classes and methods.
I have also tested the other most up-voted functions which can produce false positives.
I tested with these URLs, which points to the Visual Studio Community Installer, found on this page.
Just note that this will not work with .NET Framework, as HttpClient.Send does not exist.
To get it working on .NET Framework you will need to change
client.Send(request)
toclient.SendAsync(request).Result
.Web 服务器以 HTTP 状态代码进行响应,指示请求的结果,例如 200(有时 202)表示成功,404 - 未找到等(请参阅 此处)。 假设 URL 的服务器地址部分是正确的,并且您没有收到套接字超时,则异常很可能会告诉您 HTTP 状态代码不是 200。我建议检查异常的类并查看异常是否携带HTTP 状态代码。
IIRC - 有问题的调用抛出 WebException 或后代。 检查类名以查看是哪个类,并将调用包装在 try 块中以捕获条件。
Web servers respond with a HTTP status code indicating the outcome of the request e.g. 200 (sometimes 202) means success, 404 - not found etc (see here). Assuming the server address part of the URL is correct and you are not getting a socket timeout, the exception is most likely telling you the HTTP status code was other than 200. I would suggest checking the class of the exception and seeing if the exception carries the HTTP status code.
IIRC - The call in question throws a WebException or a descendant. Check the class name to see which one and wrap the call in a try block to trap the condition.
我有一个更简单的方法来确定 url 是否有效。
i have a more simple way to determine weather a url is valid.
根据已经给出的示例,我想说,最好的做法是将响应包装在这样的使用中
Following on from the examples already given, I'd say, it's best practice to also wrap the response in a using like this