当我收到 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。
感谢任何人都可以提供的任何帮助。