如何使用 HttpWebRequest 在 Windows 服务应用程序中获取网页的加载时间

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

我正在寻找无需在 Windows 服务应用程序中使用 WebBrowser() 即可帮助我获取网页加载时间的代码。

我运行通过不同的方法,但我不太明白。

请帮我解决这个问题。

这个函数应该可以解决问题:

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

这里只考虑源代码的下载。如果你想计算下载源代码和呈现页面需要多长时间,你必须使用 WebBrowser class.

工作原理:

该函数声明并启动一个 Stopwatch,它将用于计算操作花费的时间,然后它创建一个到指定 URL 的 Web 请求。它下载整个页面的源代码(通过 HttpWebResponse),然后检查响应的 StatusCode.

StatusCode.OK(HTTP 状态代码 200)表示请求成功并且请求的信息(网页的源代码)在响应中,但我们不会使用源代码我们让响应稍后由 Using/End Using 块处理的任何代码。

最后,该函数停止向您提供 Stopwatch 和 returns 已用时间(下载网页源代码所花费的时间)。

使用示例:

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