在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
處理錯誤。