[英]C# - Getting the response body from a 403 error
從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.
}
任何幫助,將不勝感激。 謝謝。
您正在尋找WebException.Response
屬性:
catch(WebException ex)
{
var response = (HttpWebResponse)ex.Response;
}
這對我有用..
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.