任何方式使用Web客户端时,服务器返回一个错误访问响应体? [英] Any way to access response body using WebClient when the server returns an error?

查看:125
本文介绍了任何方式使用Web客户端时,服务器返回一个错误访问响应体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来访问响应身体的时候响应状态是4XX使用WebClient类的时候,例如:

(Web客户端,EVT)=> //这是事件处理程序UploadStringCompleted事件     {         如果(evt.Error!= NULL)         {             //我可以访问响应文本?         }     });

解决方案

由于evt.Error是一个WebException(而不是香草例外),这是我做的(请原谅VB.NET):

'''<总结> '''扩展了WebException包括从.Message HTTP响应的任何正文 '''< /总结> 好友功能ExtendWebExceptionInfo(前作为例外)作为例外     昏暗WEX作为WebException = TryCast(例如,WebException)     如果WEX是Nothing然后返回前     昏暗exMessage作为字符串=无     使用阅读器作为新的StreamReader(wEx.Response.GetResponseStream,System.Text.Encoding.UTF8)         exMessage = reader.ReadToEnd     结束使用     如果不String.IsNullOrWhiteSpace(exMessage)然后         exMessage =的String.Format({0} {1} {1}服务器说:{1} {2},wEx.Message,vbCrLf,exMessage)         返回新WebException(exMessage,WEX,wEx.Status,wEx.Response)     结束如果     返回WEX 端功能

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

这篇关于任何方式使用Web客户端时,服务器返回一个错误访问响应体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆