当状态不是200时,如何从Web请求中读取响应?

当我收到web异常时,我无法从vb.net中的HTTP Web请求获取响应文本。

这是我正在做的代码。

Try
            myWebResponse = CType(request.GetResponse(), HttpWebResponse)
            myStreamReader = New StreamReader(myWebResponse.GetResponseStream())

            ResponseText = myStreamReader.ReadToEnd
            If myWebResponse.StatusCode = HttpStatusCode.Accepted Or myWebResponse.StatusCode = 200 Then
                SendResult = True 'Sent 
                SendStatus = 1 'message sent successfully
                Try
                    Integer.TryParse(myWebResponse.Headers("Number-Of-MT-PDU"), num_MT_PDU)
                Catch ex As Exception
                End Try
            Else
                SendStatus = 2 'message processed but not sent successfully
            End If
        Catch e As WebException
            If (e.Status = WebExceptionStatus.ProtocolError) Then
                Dim response As WebResponse = e.Response
                Using (response)
                    Dim httpResponse As HttpWebResponse = CType(response, HttpWebResponse)
                    statusCode = httpResponse.StatusCode
                    Try
                        myStreamReader = New StreamReader(response.GetResponseStream())
                        Using (myStreamReader)
                            ResponseText = myStreamReader.ReadToEnd & "Status Description = " & HttpWebResponse.StatusDescription
                        End Using
                    Catch ex As Exception
                        Logger.LogError(Me, ex)
                    End Try
                End Using

令人烦恼的是,我正在联系的API使用404作为有效的响应。 如果我在浏览器中放置请求,则会显示一些消息文本。 我希望能够在我的程序中使用该文本。 我不能简单地使用错误代码来确定操作,因为我不认为我可以区分有效的404响应和实际错误。

在这行代码中

myWebResponse = CType(request.GetResponse(), HttpWebResponse)

抛出异常。

在例外情况下,我可以获取404代码和描述,但不能获得响应流。 它始终为空。

如果我得到一个200响应,我得到响应流中的文本没有问题。

在Web异常响应对象(在Visual Studios调试器中)中,我检查了标题和对象值,并且无法在任何地方找到响应文本。 如果我在浏览器中粘贴请求URL,即使它是404,我也会收到回复文本。

小提琴手的原始回应:

HTTP/1.1 404 Not Found Connection: close Content-Type: text/plain; charset=UTF-8 Content-Length: 35 "The response Message"

关于如何在我的程序中获得“回复消息”的任何想法? 我必须在服务器上使用.Net。

感谢任何人的帮助。


此LINQPad查询正常工作,转储由我的Web服务器的“未找到”错误网页提供的HTML:

Dim rq = System.Net.WebRequest.Create(New Uri("http://localhost/test"))
Try 
  Dim rs = rq.GetResponse
  rs.Dump
Catch Ex As System.Net.WebException
 Dim rs = Ex.Response
 Call (New StreamReader(rs.GetResponseStream)).ReadToEnd.Dump
End Try

仅供参考,除了推测的错误HttpWebResponse.StatusDescription (并注释掉“无关的东西”),再次作为LINQPad查询(在.NET 4.0中):

Dim request = WebRequest.Create("http://localhost/test")
Dim myStreamReader As StreamReader
Dim SendStatus As Integer = -1
Dim statusCode As HttpStatusCode
Dim ResponseText As String
Try
    Dim myWebResponse = CType(request.GetResponse(), HttpWebResponse)
        myStreamReader = New StreamReader(myWebResponse.GetResponseStream())

        ResponseText = myStreamReader.ReadToEnd
        If myWebResponse.StatusCode = HttpStatusCode.Accepted Or myWebResponse.StatusCode = 200 Then
            'SendResult = True 'Sent 
            SendStatus = 1 'message sent successfully
            'Try
            '    Integer.TryParse(myWebResponse.Headers("Number-Of-MT-PDU"), num_MT_PDU)
            'Catch ex As Exception
            'End Try
        Else
            SendStatus = 2 'message processed but not sent successfully
        End If
    Catch e As WebException
        If (e.Status = WebExceptionStatus.ProtocolError) Then
            Dim response As WebResponse = e.Response
            Using (response)
                Dim httpResponse As HttpWebResponse = CType(response, HttpWebResponse)
                statusCode = httpResponse.StatusCode
                Try
                    myStreamReader = New StreamReader(response.GetResponseStream())
                    Using (myStreamReader)
                        ResponseText = myStreamReader.ReadToEnd & "Status Description = " & httpResponse.StatusDescription ' HttpWebResponse.StatusDescription
                    End Using
                Catch ex As Exception
                    'Logger.LogError(Me, ex)
                    ex.Dump("Exception")
                End Try
            End Using
      End If
End Try
ResponseText.Dump("ResponseText")

我还确认了上述代码(通过添加推断的As子句并将.Dump调用转换为Console.WriteLine )可以在VB 2.0中使用.NET 2.0。


请注意,关键在于,即使GetResponseStream()的行为抛出.NET WebException,HttpWebResponse实际上也会传递给WebException对象,因此,在Catch中,您将对WebException.Response对象执行新的GetResponseStream()。

下面,在初始化GetResponseStream()的Catch时非常类似的代码,

   Try 
            OriginalResponseStream = GetResponseStream(OriginalHTTPWebResponse)

   Catch wex as WebException
            Dim response As WebResponse = wex.Response
            Dim statusCode As HttpStatusCode
            Dim ResponseText As String

            Dim httpResponse As HttpWebResponse = CType(response, HttpWebResponse)
            statusCode = httpResponse.StatusCode

            Try

                Dim myStreamReader As New StreamReader(response.GetResponseStream())
                Using (myStreamReader)
                    ResponseText = myStreamReader.ReadToEnd
                    Process(ResponseText) '<===as in whatever you need to do with the response
                End Using
            Catch ex As Exception

                HandleIt(ex.Message) '<===as in whatever you want to do if Exception during the above

            End Try

   End Try
链接地址: http://www.djcxy.com/p/54629.html

上一篇: How can I read the response from a web request when the Status is not 200?

下一篇: MongoDb : Avoid excessive disk space