在以下代码中我试图处理不同的服务器目标: 此函数用于从网页读取xml或html soruce 在注释行中,我得到“对象引用未设置为对象的实例”。 我想知道为什么。
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
写为
objResponse = objRequest.GetResponse
除了我得到错误403或503的异常,我不知道如何处理它。
答案 0 :(得分:1)
您的错误行:
Select Case CType(objResponse, Net.HttpWebResponse).StatusCode
objResponse
分配任何内容即可调用。
您需要将其更改为:
objResponse = objRequest.GetResponse
Select Case CType(objResponse, Net.HttpWebResponse).StatusCode`
关于获取您尝试ftech的页面的HTTP错误代码,以下是它们的含义及其原因:
答案 1 :(得分:1)
首先,tcarvin是正确的,你的问题的代码缺少这一行:
objResponse = objRequest.GetResponse
其次,您可以这样做来解决您的其他问题:
If Not objResponse Is Nothing Then
'Select Case Code
Else
'Handle failure.
End If