【问题标题】:C# - Getting the response body from a 403 errorC# - 从 403 错误中获取响应正文
【发布时间】:2015-06-06 12:45:55
【问题描述】:

从 URL 请求数据时收到 403 错误。这是意料之中的,我不是在问如何纠正它。
将此 URL 直接粘贴到我的浏览器时,我会得到一个基本信息字符串,描述为什么拒绝权限。
我需要通过我的 C# 代码阅读此基本错误消息,但是当发出请求时,会引发 System.Net.WebException ("The remote server returned an error: (403) Forbidden.") 错误,并且响应正文我无法使用。

是否可以简单地抓取页面内容而不抛出异常? 相关代码几乎是您所期望的,但无论如何都在这里。

   HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(sPageURL);

   try
   {
        //The exception is throw at the line below.
        HttpWebResponse response = (HttpWebResponse)(request.GetResponse());

        //Snipped processing of the response.
   }
   catch(Exception ex)
   {
        //Snipped logging.
   }

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 您应该将您的response 包装在using 语句中。
  • 我一直不明白using 的意思。它只在其范围内声明一个对象,对吗?我的方法和 try/catch 块无论如何都会这样做,不是吗?
  • using 确保对象将立即被释放,而不是等待 GC(它会生成一个 finally 块)。
  • @SLaks:注意。感谢您的提示。

标签: c# http httpwebrequest


【解决方案1】:

您正在寻找WebException.Response 属性:

catch(WebException ex)
{
     var response = (HttpWebResponse)ex.Response;
}

【讨论】:

  • 如此简单!工作完美。谢谢。
  • 只是补充一下,当你得到响应后,你可以像往常一样得到流:response.GetResponseStream()
【解决方案2】:

这对我有用..

HttpWebResponse httpResponse;
            try
            {
                httpResponse = (HttpWebResponse)httpReq.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException e)
            {
                Console.WriteLine("This program is expected to throw WebException on successful run." +
                                    "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    using (Stream data = e.Response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 2012-05-10
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多