zoukankan      html  css  js  c++  java
  • C#使用WebClient时,如果状态码不为200时,如何获取请求返回的内容


    一、事故现场

    使用WebClient发送请求,如果返回的状态码不是2xx或3xx,那么默认情况下会抛出异常,
    那如何才能获取到请求返回的内容呢?

    二、解决方法

    可以通过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 异常,然后再判断异常类型;

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

  • 相关阅读:
    杂想
    杂题操作
    codeforces 11D(状压dp)
    2019 计蒜之道 复赛 “星云系统” (单调栈)
    SPOJ VLATTICE (莫比乌斯反演)
    2019 ICPC 陕西西安邀请赛 D. Miku and Generals
    buerdepepeqi 的模版
    HDU 2588 GCD
    二项式反演
    2014ACM/ICPC亚洲区西安站 F题 color (组合数学,容斥原理)
  • 原文地址:https://www.cnblogs.com/willingtolove/p/12078698.html
Copyright © 2011-2022 走看看