When using the WebClient C #, if the status code 200 is not, how to obtain the return of the content request


First, the scene of the accident

Use WebClient request is sent, if not return a status code of 2xx or 3xx, then the default will throw an exception,
how can you get into the content requested to return it?

Second, the solution

Try catch acquired by WebException types of exceptions;

  • api interfaces:
   [HttpGet("test")]
   public ActionResult test()
   {
       Response.StatusCode = 401;
       return Content("test");
   }
  • Sending a request using WebClient:
    1: Direct capture WebException exception type;
   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 "";
       }
   }

Method two: capturing Exception exception, and then determine the type of anomaly;

   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 "";
       }
   }

Guess you like

Origin www.cnblogs.com/willingtolove/p/12078698.html