检查URL是否包含有效页面

时间:2017-12-21 15:30:32

标签: vb.net url httpwebrequest response

我想检查网址是否有效页面(不是404,只有200)。

Code I尝试过:

Dim request As HttpWebRequest = DirectCast(WebRequest.Create(myurl), HttpWebRequest)
request.KeepAlive = True
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
If response.StatusCode = HttpStatusCode.OK Then
    MsgBox("OK")
End If

然而,即使我输入http://mywebsite.com/blahblah,我输入的每个网址都会留下OK响应。

在所有网站上都不一样(与example.com一起使用),但它在我的网站上无效。的为什么吗

在我的浏览器中,我看到404页面,但代码说它确定

编辑:提一下我的网站上有Cloudflare。

2 个答案:

答案 0 :(得分:0)

尝试一下,看看它是否适合你......正如我在评论中提到的那样:

  

404只是意味着在服务器上找不到页面,即使找不到页面并且已到达并响应了服务器,状态也会返回

Public Class WebPage
        Public Property PageSource As String = String.Empty
        Public Property Status As HttpStatusCode = HttpStatusCode.NotFound
        Public Property WebError As String = String.Empty
    End Class

    Public Shared Function GetWebPage(ByVal Website As String) As WebPage
    Dim web As New WebPage() With {.Status = HttpStatusCode.OK}
    Try
        Using source As New System.Net.WebClient()
            web.PageSource = source.DownloadString(Website)
        End Using

        Return web
    Catch exweb As WebException
        If exweb.Status = WebExceptionStatus.ProtocolError AndAlso exweb.Message.Contains("404") Then
            web.Status = HttpStatusCode.NotFound
        Else
            web.Status = HttpStatusCode.BadRequest            
        End If
        web.WebError = exweb.Message
    Catch ex As Exception
        web.Status = HttpStatusCode.NotFound
        web.WebError = ex.Message
    End Try

    Return web
End Function

使用示例

Dim webObj As WebPage = GetWebPage("THESITE")
If Not String.IsNullOrEmpty(webObj.WebError) Then
   MessageBox.Show(webObj.WebError)
ElseIf webObj.Status = HttpStatusCode.OK Then
   MessageBox.Show("OK")
End If

答案 1 :(得分:0)

这将做你想要的。

Function URLExists(url As String) As Boolean
    Dim Request As Object
    Dim ff As Integer
    Dim rc As Variant

    On Error GoTo EndNow
    Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")

    With Request
      .Open "GET", url, False
      .send
      rc = .StatusText
    End With
    Set Request = Nothing
    If rc = "OK" Then URLExists = True

    Exit Function
EndNow:
End Function