0

私は自分のウェブサイトから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 が表示されない理由がわかりませんが、デバッガーにエラーが表示されます。

4

1 に答える 1

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
于 2012-09-05T21:04:05.553 に答える