在下面的代码中,我试图处理不同的服务器响应:此函数用于从网页读取 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 语句并只写objResponse
as
objResponse = objRequest.GetResponse
除了我得到错误 403 或 503 的异常,我不知道如何处理这个问题。