0

在下面的代码中,我试图处理不同的服务器响应:此函数用于从网页读取 xml 或 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

        Select Case CType(objResponse, Net.HttpWebResponse).StatusCode 'Here is where i get the error Object reference not set to an instance of an object.

    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

        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

现在当我删除 switch 语句并只写objResponseas

objResponse = objRequest.GetResponse

除了我得到错误 403 或 503 的异常,我不知道如何处理这个问题。

4

2 回答 2

1

您的错误行:

Select Case CType(objResponse, Net.HttpWebResponse).StatusCode

被调用而没有分配任何东西给objResponse.

您需要将其更改为:

objResponse = objRequest.GetResponse

Select Case CType(objResponse, Net.HttpWebResponse).StatusCode`

关于获取您尝试访问的页面的 HTTP 错误代码,以下是它们的含义及其原因:

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

于 2012-09-06T17:34:55.140 回答
1

首先, tcarvin 是正确的,您的问题代码缺少这一行:

objResponse = objRequest.GetResponse

其次,您可以这样做来解决您的其他问题:

    If Not objResponse Is Nothing Then

        'Select Case Code

    Else

        'Handle failure.

    End If
于 2012-09-06T18:07:21.560 回答