首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

WebException如何获取整体响应?

在处理WebException时,如果需要获取整体响应,可以使用以下方法:

  1. 使用HttpWebResponse对象获取响应信息:
代码语言:csharp
复制
try
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // 处理响应信息
}
catch (WebException ex)
{
    if (ex.Response != null)
    {
        HttpWebResponse errorResponse = (HttpWebResponse)ex.Response;
        // 获取整体响应信息
        Console.WriteLine("Error code: {0}", errorResponse.StatusCode);
        Console.WriteLine("Error message: {0}", errorResponse.StatusDescription);
        using (Stream data = errorResponse.GetResponseStream())
        using (StreamReader reader = new StreamReader(data))
        {
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine("Error response: {0}", responseFromServer);
        }
    }
    else
    {
        Console.WriteLine("No response received from server.");
    }
}
  1. 使用HttpClient对象获取响应信息:
代码语言:csharp
复制
using (HttpClient client = new HttpClient())
{
    try
    {
        HttpResponseMessage response = client.GetAsync("http://www.example.com").Result;
        response.EnsureSuccessStatusCode();
        // 处理响应信息
    }
    catch (HttpRequestException ex)
    {
        if (ex.InnerException is WebException webEx)
        {
            if (webEx.Response != null)
            {
                HttpWebResponse errorResponse = (HttpWebResponse)webEx.Response;
                // 获取整体响应信息
                Console.WriteLine("Error code: {0}", errorResponse.StatusCode);
                Console.WriteLine("Error message: {0}", errorResponse.StatusDescription);
                using (Stream data = errorResponse.GetResponseStream())
                using (StreamReader reader = new StreamReader(data))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine("Error response: {0}", responseFromServer);
                }
            }
            else
            {
                Console.WriteLine("No response received from server.");
            }
        }
        else
        {
            Console.WriteLine("An error occurred while sending the request.");
        }
    }
}

以上代码示例展示了如何使用HttpWebResponse和HttpClient对象获取WebException中的整体响应信息。在处理异常时,可以通过WebException的Response属性来获取HttpWebResponse对象,从而获取响应信息。在使用HttpClient时,可以通过捕获HttpRequestException异常并检查其InnerException是否为WebException来获取响应信息。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券