【问题标题】:vb.net Handling the server response when trying to read xml from some pagevb.net 尝试从某个页面读取 xml 时处理服务器响应
【发布时间】:2012-09-05 19:54:32
【问题描述】:

我有以下函数用于从我的网站获取 html 源代码

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

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

            Try
                objResponse = objRequest.GetResponse 'some times it gives an error server unavailable 503
            Catch ex As WebException
                MsgBox(ex.Message)
            End Try

            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
        Catch
            ' Error occured grabbing data, simply return nothing
            Return ""
        End Try
    End Function

有时 objResponse 会给出错误“503 服务器不可用”和许多其他错误,如 403 等,我该如何独立处理这些错误?

我怎样才能让这个函数在一段时间后重试请求?问题是 try 语句似乎没有处理这个问题,我不确定为什么我没有看到异常 MsgBox 但它在调试器上显示错误。

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    将响应转换为 HttpWebResponse 对象并对其 StatusCode 属性执行 Select Case。你必须清理并完成它,但这里有一个例子:

        Select Case CType(objResponse, Net.HttpWebResponse).StatusCode
    
            Case Net.HttpStatusCode.InternalServerError
                'This is sloppy, but a quick example for one of your sub-questions.
                System.Threading.Thread.Sleep(10000)
                'Try again.
                objResponse = objRequest.GetResponse
            Case Net.HttpStatusCode.BadRequest
                'Error Handling
            Case Net.HttpStatusCode.OK
                'Proceed as normal.
            Case Else
                'Error Handling
    
        End Select
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      相关资源
      最近更新 更多