[英]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.