C# - 从403错误中获取响应正文

时间:2011-03-23 17:19:23

标签: c# http httpwebrequest

从URL请求数据时,我收到403错误。这是预期的,我不会问如何纠正它 将此URL直接粘贴到我的浏览器中时,我会获得一个基本信息字符串,用于描述拒绝权限的原因。
我需要通过我的C#代码读取此基本错误消息,但是当发出请求时,System.Net.WebException(“远程服务器返回错误:(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.
   }

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

2 个答案:

答案 0 :(得分:29)

您正在寻找WebException.Response财产:

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

答案 1 :(得分:3)

这对我有用..

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