Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check for a valid URL 1

Status
Not open for further replies.

solepixel

Programmer
Joined
May 30, 2007
Messages
111
Location
US
I have a URL that I must check to see if it's working before following through with some other code relative to the URL. So what I need is a function that will return True or False if the URL works or not. I tried this, but it doesn't seem to work:
Code:
Public Shared Function UrlIsValid(ByVal smtpHost As String) As Boolean
	Dim br As Boolean = False
	Try
		Dim ipHost As Net.IPHostEntry = Dns.GetHostEntry(smtpHost)
		br = True
	Catch se As Net.Sockets.SocketException
		br = False
	End Try
	Return br
End Function
 
This should work for you:

Code:
Dim httpReq As HttpWebRequest = CType(WebRequest.Create("[URL unfurl="true"]http://www.someurl.com"),[/URL] HttpWebRequest)
httpReq.AllowAutoRedirect = False
       
Dim httpRes As HttpWebResponse = CType(httpReq.GetResponse(), HttpWebResponse)
       
If httpRes.StatusCode = HttpStatusCode.OK Then
    ' everything works so do something
End If

Regards,

-Kevin
 
This seems to work when the URL is OK, however when it's broken, the page shows up:
Server Error in '/' Application.
The remote name could not be resolved: '
I'm trying to keep my application from breaking when the URL is not working. Can this be done?
 
Just create a boolean and throw the code in a try/catch like so:

Code:
Dim httpReq As HttpWebRequest = CType(WebRequest.Create("[URL unfurl="true"]http://www.someurl.com"),[/URL] HttpWebRequest)
        httpReq.AllowAutoRedirect = False
        Dim httpRes As HttpWebResponse
        Dim exists As Boolean = False
        Try
            httpRes = CType(httpReq.GetResponse(), HttpWebResponse)
            If httpRes.StatusCode = HttpStatusCode.OK Then
                exists = True
            End If
        Catch ex As Exception

        End Try

        If exists Then
            'do something     
        End If

Regards,
-Kevin
 
Ah, ok, that's what I had wrong. I didn't do the "Try" part. Sorry, i'm a new ASP.NET user.
 
no worries, that is what the forum is here for.

Good luck,

-Kevin
 
I agree that you normally wouldn't want to use Try/Catch blocks to control flow of execution. However, in order to achieve this goal, this is the only approach I can think of. Do you know of a better practice or have a suggestion to improve ?
 
In fact, here's a couple of MS articles on the subject:


In my opinion, it would be a much better solution than wrapping the code in a Try/Catch block as a server not existing isn't really an exception if you are expecting it to happen sometimes.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
It seems to me that this is no more efficient, giving the fact you are making 2 extra network hops. Additionally, if you consider the added complexity in using sockets, it may not be the preferred approach for a self-professed newbie. Nonetheless, I still do agree that under normal circumstances using try/catch blocks this way is not a preferred method. I would bet though that if you ran the two side by side mine would be faster.

-Kevin
 
Microsoft said:
General exception handling guidelines

* Do not catch general exception types like System.Exception and System.SystemException
* Choose exceptions over error codes.
* Do not use exception handling for flow of control, only for failure situations.
* Document all exceptions thrown by a publicly callable members. (see exception element in XML documentation comments).
* Do not have publicly callable members throw or not throw based upon a parameter.
* Do you use exceptions as return values or out parameters (this is an error code).
* Avoid throwing exceptions from finally blocks.
* Avoid throwing exceptions from constructors.
* Do not rethrow by throwing the same exception object. This causes the stack trace for the original exception to be lost--use a lone "throw;" statement (without an object following it) to "rethrow" a catch exception.
There has been fairly clear instructions from Microsoft on handling exceptions and I think it's wise to stick to what they suggest, after all they built the framework and know how it should be used. To me, a failure isn't something that you are expecting and in this case we know it is a possible result. Going on that basis, we should try to handle the result of the call not cause an exception to something that isn't exceptional.

Additionally, if you consider the added complexity in using sockets, it may not be the preferred approach for a self-professed newbie.
The articles I linked to give a consise step by step approach on how to test their code which I'm sure anyone can copy/paste. Just because other methods are easier to implement and less code doesn't mean they should be used instead of something that gives you better performance. If anything, this theory is what we should be promoting to newcomers so they can get the best out of their applications.

I would bet though that if you ran the two side by side mine would be faster.
What makes you say that? I haven't tried it but I would have thought that as you can set the default timeout in the articles I linked to, that that statement wouldn't be true. The extra time for your code to wait and see if a result is returned, then create an exception, store it in memory and throw it must be longer than a value that you have control over and can set to whatever you want.

The examples I gave (i.e. pinging to see if a server responds) are simply one method that I could think of when you asked what else could be done. I'm sure that there will be others that you can use that aren't as expensive as the one you suggested.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Touche, your response was well thought out and well written. Please note though, in all of my responses to you, I agreed with the best practices.

One thing worth mentioning about pinging though; not all servers will accept pings which would render this solution useless. As far as there being a better way, I'm sure you're right and I will being researching and will soon post.

Cheers,

-Kevin
 
Please note though, in all of my responses to you, I agreed with the best practices.
You did yes, and I'm sure there will be a suggested method (although I admit I don't know what that is yet!).

not all servers will accept pings which would render this solution useless
Good point, and it may well be that it isn't a solution that should be used. Post back if you do find anything as I'm sure we will all benefit from it.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top