C# – 从403错误中获取响应正文
从URL请求数据时,我收到403错误。 这是预期的,我不会问如何纠正它。
将此URL直接粘贴到我的浏览器中时,我会获得一个基本信息串,用于描述拒绝权限的原因。
我需要通过我的C#代码读取这个基本错误消息,但是当发出请求时,System.Net.WebException(“远程服务器返回错误:(403)Forbidden。”)抛出错误,并且响应正文我无法使用。
是否可以简单地抓取页面的内容而不抛出exception? 相关的代码几乎是你所期望的,但无论如何它都在这里。
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. }
任何帮助,将不胜感激。 谢谢。
您正在寻找WebException.Response
属性:
catch(WebException ex) { var response = (HttpWebResponse)ex.Response; }
这对我有用..
上述就是C#学习教程:C# – 从403错误中获取响应正文分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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." + "nnException 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); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1033616.html