在vb.net中使用select statment的handlin Net.WebResponse

时间:2012-09-09 22:32:04

标签: vb.net try-catch httpwebresponse

我有以下函数从某个页面获取html或xml源代码,当有403异常时我发现代码没有继续到select语句

   Public Function GetPageHTML(ByVal URL As String, _
        Optional ByVal TimeoutSeconds As Integer = 10) _
        As String
        ' Retrieves the HTML from the specified URL,
        ' using a default timeout of 10 seconds
        Dim objRequest As Net.WebRequest
        Dim objResponse As Net.WebResponse
        Dim objStreamReceive As System.IO.Stream
        Dim objEncoding As System.Text.Encoding
        Dim objStreamRead As System.IO.StreamReader


        ' Setup our Web request
        objRequest = Net.WebRequest.Create(URL)
        objRequest.Timeout = TimeoutSeconds * 5000
        ' Retrieve data from request

Try
        objResponse = objRequest.GetResponse 'some times it gives an error server unavailable 503

        Select Case CType(objResponse, Net.HttpWebResponse).StatusCode
            Case Net.HttpStatusCode.RequestTimeout
                Return "BadRequest"
            Case 403
                Return "BadRequest"
            Case Net.HttpStatusCode.GatewayTimeout
                Return "BadRequest"
            Case Net.HttpStatusCode.InternalServerError
                Return "BadRequest"
            Case Net.HttpStatusCode.BadRequest
                Return "BadRequest"
            Case Net.HttpStatusCode.OK

                objStreamReceive = objResponse.GetResponseStream
                objEncoding = System.Text.Encoding.GetEncoding( _
                    "utf-8")

                objStreamRead = New System.IO.StreamReader( _
                    objStreamReceive, objEncoding)
                ' Set function return value

                GetPageHTML = objStreamRead.ReadToEnd()
                ' Check if available, then close response
                If Not objResponse Is Nothing Then
                    objResponse.Close()
                End If
            Case Else
                MsgBox("Case Else")

        End Select
catch
Return ""
End Try
    End Function

所以我该如何解决这个问题?调试器显示此行中的异常

objResponse = objRequest.GetResponse 'some times it gives an error server unavailable 503 or 403

所以它不会去选择陈述

也是第二次尝试同样的问题,它没有捕获错误,并没有显示异常消息 enter image description here

0 个答案:

没有答案