在HttpWebRequest中忽略401 Unathorized

时间:2015-06-29 10:43:52

标签: c# httpwebrequest http-status-code-401

第三方网站在其常规工作流程中返回401而不是200。浏览器忽略401并显示收到的HTML内容,因此用户甚至不知道有401.但是HttpWebRequest会抛出HttpException。如何忽略它并获得响应?

1 个答案:

答案 0 :(得分:2)

您的代码抛出WebException,因此获得结果的解决方案是:将整个代码放在try catch块中,catch块必须捕获WebException,并在catch块中编写以下代码以获取html内容。< / p>

    try
    {
      // your code here
    }                
    catch (WebException e2)
    {
       using (WebResponse response = e2.Response)
        {
         HttpWebResponse httpResponse = (HttpWebResponse)response;
         Console.WriteLine(" Error : {0}", httpResponse.StatusCode);
         using (Stream data = response.GetResponseStream())
         using (var reader = new StreamReader(data))
         {  
//the html content is here
            string text = reader.ReadToEnd();
            Console.WriteLine(text);
         }
        }
}