vb.nethttpwebrequestgetresponse

response using httpwebrequest and uri problems


I'm trying to test if a website is up or down and I ran into some problems.

First I know if I'm to test the status of the server it's possible to do it with a simple piece of code like:

If My.Computer.Network.Ping(TextBox1.Text) Then
        TextBox2.Text = "Online"
    Else
        TextBox2.Text = "Offline"
    End If

But i refuse to do so since Pings are not always a reliable method of determining if an external web server is up.

So i try to work this out using this code:

Try
        Dim fr As System.Net.HttpWebRequest
        Dim targetURI As New Uri(TextBox1.Text)
        fr = DirectCast(System.Net.HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
        If (fr.GetResponse().ContentLength > 0) Then
            TextBox2.Text = "Website appears to exist!"
        Else
            TextBox2.Text = "Website appears to have no content at all!"
        End If
    Catch ex As System.Net.WebException
        TextBox2.Text = "Cannot connect - website not responding!"

End Try

That code works. But the problem is if I type http://google.com in the TextBox1 and try to get server status then sometimes it shows up as "Website appears to have no content at all!" even when http://google.com is online and have contents. Not just for google but for other sites as well.

I have two question regarding this code.

  1. Why does it tells me that "Website appears to have no content at all!" even when http://google.com or any other site is online and have contents?

  2. Suppose i type in just google.com or any site without http:// or https:// in TextBox1 it gives me an error saying invalid URI format. Is there anyway I could automatically add http:// or https:// to the beginning of the url entered in TextBox1?

I know I can add this to the above code to do that:

Dim baseAddressx As String = "http://"
Dim targetURI As New Uri(baseAddressx & TextBox1.Text) 

but what if I type http://google.com when the code it self adds http:// that will make a problem. Any better way to achieve that?


Solution

  • What I think you should do is that you should read the Status Code of the response, not the content length. It can be read as follows:

    HttpWebResponse res = (HttpWebResponse)fr.GetResponse(); int statusCode = (int)response.StatusCode if(statusCode == 200) //Website is up else.

    You may create enums to have a good understanding of it. And respond in various ways to the user based on which value you get. Hope that helps.

    Sorry I am no expert in VB. I know C#, I hope you can convert this to VB easily. See here.