[英]Get detailed HTTP Response in C#
我正在使用Selenium對我的網站進行一些自動測試。 如果網站之一或網站中的頁面之一關閉,我需要將錯誤代碼和描述保存在文件中。 我成功使用了StatusCode和StatusDescription,但是它們都給了我相同的模糊輸出。 例如,一個404錯誤給出:協議錯誤。 下面是我的代碼。 有任何想法嗎?
public static void GetPage(String url)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("Report.txt", true);
String result;
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for a response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
{
file.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}", myHttpWebResponse.StatusDescription);
}
else file.WriteLine("\r\nResponse Status Code is NOT OK and StatusDescription is: {0}", myHttpWebResponse.StatusCode);
result = myHttpWebResponse.StatusDescription;
// HttpListenerResponse response1 = response;
// Releases the resources of the response.
myHttpWebResponse.Close();
file.Close();
}
catch (WebException e)
{
file.WriteLine("\r\nWebException Raised. The following error occurrrrrrrrrrred : {0}", e.Status);
file.Close();
}
catch (Exception e)
{
file.WriteLine("\nThe following Exception was raised : {0}", e.Message);
file.Close();
}
}
}
myHttpWebResponse.StatusCode
是一個枚舉,其中成員的值與HTTP狀態代碼匹配,例如
public enum HttpStatusCode
{
...
OK = 200
Moved Permanently= 301,
Moved Temporarily= 302,
Forbidden= 403,
...
}
您可以通過訪問(int)myHttpWebResponse.StatusCode
來獲取錯誤代碼
然而
您還必須檢查響應是否由於服務器錯誤而失敗(WebException提供了WebResponse)。
將您的WebException catch循環更改為以下內容:
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
file.WriteLine("\r\nWebException Raised. The following error occurrrrrrrrrrred : {0}", (int)myHttpWebResponse.StatusCode);
}
else
{
file.WriteLine("Error: {0}", e.Status);
}
file.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.