在处理WebException时,如果需要获取整体响应,可以使用以下方法:
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.");
}
}
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来获取响应信息。
领取专属 10元无门槛券
手把手带您无忧上云