0

我在从响应中获取 HttpStatusCode 时遇到小问题。问题是当文件存在时我得到响应并且可以读取读取状态,但是当文件不存在时我看不到任何状态,即使我要求显示状态字符串。这是我的代码:

 Dim urls As New List(Of String)
        urls.Add("http://www.domain.com/test.php")
        urls.Add("http://www.domain.com/test2.php")
        urls.Add("http://www.domain.com/index.php")


        For Each Url As String In urls
            Dim response As HttpWebResponse = Nothing
            Try
                Dim request As HttpWebRequest = Net.HttpWebRequest.Create(Url)
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
                request.Method = "GET"
                response = request.GetResponse()

            Catch webex As WebException
            End Try

            If response.StatusCode = HttpStatusCode.OK = True Then
                MsgBox("File Url is correct: " & response.StatusCode.ToString)
            ElseIf response.StatusCode = HttpStatusCode.NotFound = True Then
                MsgBox("File Url is incorrect: " & Url)
            Else
                MsgBox(response.StatusCode.ToString)
            End If
        Next
4

3 回答 3

2

当服务器没有返回成功状态码(2xx)时,框架总是抛出异常。但是,您仍然可以从异常对象中获得响应。

Function GetResponse(url As Uri) As WebResponse
    Dim response As WebResponse
    Dim request As HttpWebRequest = HttpWebRequest.Create(url)
    Try
        response = request.GetResponse()
    Catch serverErrors As WebException When serverErrors.Response IsNot Nothing
        response = serverErrors.Response
    Catch otherExceptions As Exception
        DoSomethingWith(otherExceptions)
    End Try
    Return response
End Function
于 2013-07-11T18:20:02.257 回答
2

问题是当文件不存在时,它会生成一个 WebException,并且您的代码会默默地“吞下”这些异常。IE。它抓住了它,什么也不做。

您需要添加一些代码来检查您的 catch 语句中的错误。

这可能是如何在 .NET 中正确捕获 404 错误的副本 (尽管是 C# 而不是 VB)

于 2013-07-11T13:25:25.367 回答
0

如果我错了,请纠正我,但不应该这部分:

ElseIf response.StatusCode = HttpStatusCode.NotFound = True Then
           MsgBox("File Url is incorrect: " & Url)

实际上是:

ElseIf response.StatusCode = HttpStatusCode.NotFound = True Then
           MsgBox("File Url is incorrect: " & Url & response.StatusCode.ToString)

如果你想StatusCode显示。

关于您的评论:

但是当文件不存在时,我看不到任何状态

代码正在命中NotFound枚举并输入代码块,但您并没有准确地显示代码中的状态。

于 2013-07-11T11:31:33.680 回答