在C#中,使用HttpWebRequest
处理错误的方法如下:
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);
}
}
}
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Error: " + response.StatusCode);
}
else
{
// 处理成功的响应
}
StreamReader
读取响应内容并进行处理。using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch
块中处理可能发生的异常,例如WebException
和其他通用异常。通过以上方法,您可以在C#中使用HttpWebRequest
处理错误。