[英]Any way to access response body using WebClient when the server returns an error?
使用WebClient類時,如果響應狀態為4xx,是否可以訪問響應主體,例如:
(webClient, evt) => // this is the event handler for the UploadStringCompleted event
{
if (evt.Error != null)
{
// can I access the response text?
}
});
由於evt.Error是WebException(而不是普通的Exception),因此,這就是我要做的(請原諒VB.NET):
''' <summary>
''' Extends a WebException to include any body text from the HTTP Response in the .Message
''' </summary>
Friend Function ExtendWebExceptionInfo(ex As Exception) As Exception
Dim wEx As WebException = TryCast(ex, WebException)
If wEx Is Nothing Then Return ex
Dim exMessage As String = Nothing
Using reader As New StreamReader(wEx.Response.GetResponseStream, System.Text.Encoding.UTF8)
exMessage = reader.ReadToEnd
End Using
If Not String.IsNullOrWhiteSpace(exMessage) Then
exMessage = String.Format("{0}{1}{1}The server says:{1}{2}", wEx.Message, vbCrLf, exMessage)
Return New WebException(exMessage, wEx, wEx.Status, wEx.Response)
End If
Return wEx
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.