在C#中,使用HttpWebRequest
處理錯(cuò)誤的方法如下:
try-catch
語(yǔ)句捕獲可能發(fā)生的異常,例如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
{
// 處理成功的響應(yīng)
}
StreamReader
讀取響應(yīng)內(nèi)容并進(jìn)行處理。using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch
塊中處理可能發(fā)生的異常,例如WebException
和其他通用異常。通過(guò)以上方法,您可以在C#中使用HttpWebRequest
處理錯(cuò)誤。