Search code examples
vb.nethttpwebrequest

How to get the loading time of a web page in Windows Service Application using HttpWebRequest


I'm looking for code that will help me get the loading time of a web page without Using WebBrowser() in a Windows Service Application.

I run through different methods, but I don't quite get it.

Please help me solve this problem.


Solution

  • This function should do the trick:

    Public Function WebpageResponseTime(ByVal URL As String) As TimeSpan
        Dim sw As New System.Diagnostics.Stopwatch
        sw.Start()
    
        Dim wRequest As WebRequest = HttpWebRequest.Create(URL)
        Using httpResponse As HttpWebResponse = DirectCast(wRequest.GetResponse(), HttpWebResponse)
            If httpResponse.StatusCode = HttpStatusCode.OK Then
                sw.Stop()
                Return sw.Elapsed
            End If
        End Using
    End Function
    

    This will only take the downloading of the source code into account. If you want to calculate how long time it takes to download the source code AND render the page you'd have to use the WebBrowser class.

    How it works:

    The function declares and starts a Stopwatch which will be used for calculating how long the operation took, then it creates a web request to the specified URL. It downloads the entire page's source code (via the HttpWebResponse) and after that checks the response's StatusCode.

    StatusCode.OK (which is HTTP status code 200) means that the request succeeded and that the requested information (the web page's source code) is in the response, but as we're not gonna use the source code for anything we let the response get disposed later by the Using/End Using block.

    And lastly the function stops the Stopwatch and returns the elapsed time (how long it took to download the web page's source) to you.

    Example use:

    Dim PageLoadTime As TimeSpan = WebpageResponseTime("http://www.microsoft.com/")
    MessageBox.Show("Response took: " & PageLoadTime.ToString())