温馨提示×

c# httpwebrequest如何处理错误

c#
小樊
104
2024-11-16 20:44:52
栏目: 编程语言

在C#中,使用HttpWebRequest处理错误的方法如下:

  1. 异常处理:使用try-catch语句捕获可能发生的异常,例如WebException
using System;
using System.IO;
using System.Net;
using System.Text;

class Program
{
    static void Main()
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
            request.Method = "GET";
            request.ContentType = "application/json";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Console.WriteLine("Error: " + response.StatusCode);
                }
                else
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        string content = reader.ReadToEnd();
                        Console.WriteLine(content);
                    }
                }
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            if (ex.Status == WebExceptionStatus.Timeout)
            {
                Console.WriteLine("The request timed out.");
            }
            else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
            {
                Console.WriteLine("The remote name could not be resolved.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}
  1. 检查HTTP状态码:在处理响应之前,检查HTTP状态码以确定请求是否成功。
if (response.StatusCode != HttpStatusCode.OK)
{
    Console.WriteLine("Error: " + response.StatusCode);
}
else
{
    // 处理成功的响应
}
  1. 读取响应内容:如果请求成功,使用StreamReader读取响应内容并进行处理。
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}
  1. 处理异常:在catch块中处理可能发生的异常,例如WebException和其他通用异常。

通过以上方法,您可以在C#中使用HttpWebRequest处理错误。

0