C#使用WebClient時,若是狀態碼不爲200時,如何獲取請求返回的內容


1、事故現場

使用WebClient發送請求,若是返回的狀態碼不是2xx或3xx,那麼默認狀況下會拋出異常,
那如何才能獲取到請求返回的內容呢?ui

2、解決方法

能夠經過try catch獲取到WebException類型的異常;編碼

  • api接口:
[HttpGet("test")]
   public ActionResult test()
   {
       Response.StatusCode = 401;
       return Content("test");
   }
  • 使用WebClient發送請求:
    方式一:直接捕獲WebException 類型異常;
public static string WebClientGetRequest(string url)
   {
       try
       {
           using (WebClient client = new WebClient())
           {
               //設置編碼格式
               client.Encoding = System.Text.Encoding.UTF8;
               //獲取數據
               var result = client.DownloadString(url);
               return result;
           }
       }
       catch (WebException ex)
       {
           using (HttpWebResponse hr = (HttpWebResponse)ex.Response)
           {
               int statusCode = (int)hr.StatusCode;
               StringBuilder sb = new StringBuilder();
               StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8);
               sb.Append(sr.ReadToEnd());
               Console.WriteLine("StatusCode:{0},Content:{1}", statusCode, sb);// StatusCode:401,Content:test
           }
           return "";
       }
   }

方法二:捕獲 Exception 異常,而後再判斷異常類型;url

public static string WebClientGetRequest(string url)
   {
       try
       {
           using (WebClient client = new WebClient())
           {
               //設置編碼格式
               client.Encoding = System.Text.Encoding.UTF8;
               //獲取數據
               var result = client.DownloadString(url);
               return result;
           }
       }
       catch (WebException ex)
       {
           if (ex.GetType().Name == "WebException")
           {
               WebException we = (WebException)ex;
               using (HttpWebResponse hr = (HttpWebResponse)we.Response)
               {
                   int statusCode = (int)hr.StatusCode;
                   StringBuilder sb = new StringBuilder();
                   StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8);
                   sb.Append(sr.ReadToEnd());
                   Console.WriteLine("StatusCode:{0},Content:{1}", statusCode, sb);// StatusCode:401,Content:test
               }
           }
           return "";
       }
   }
相關文章
相關標籤/搜索