HttpStatusCode读取问题

时间:2013-07-11 11:17:43

标签: .net vb.net

我遇到的问题是来自响应的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

3 个答案:

答案 0 :(得分:2)

问题在于,当文件不存在时,它会生成WebException,而您的代码会默默地“吞噬”这些异常。即。它捕获它并且什么都不做。

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

这可能是How to properly catch a 404 error in .NET的重复(虽然是C#而不是VB)

答案 1 :(得分: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

答案 2 :(得分: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枚举并输入代码块,但您并未在代码中显示状态。