在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); } } }
- 检查HTTP状态码:在处理响应之前,检查HTTP状态码以确定请求是否成功。
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
处理错误。