简体   繁体   中英

Any way to access response body using WebClient when the server returns an error?

Is there a way to access the response body when the response status is 4xx when using the WebClient class, for example:

(webClient, evt) => // this is the event handler for the UploadStringCompleted event
    {
        if (evt.Error != null)
        {
            // can I access the response text?
        }
    });

Since evt.Error is a WebException (rather than a vanilla Exception), here's what I do (please excuse the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM