C# 在C中获取详细的HTTP响应#

C# 在C中获取详细的HTTP响应#,c#,http-status-code-404,httprequest,httpresponse,C#,Http Status Code 404,Httprequest,Httpresponse,我正在使用Selenium为我的网站做一些自动测试。如果某个网站或某个网站中的某个页面关闭,我需要将错误代码和说明保存在文件中。 我成功地使用了StatusCode和StatusDescription,但它们都给了我相同的模糊输出。对于ex,404错误给出:协议错误。 下面是我的代码。有什么想法吗 public static void GetPage(String url) { System.IO.StreamWriter file = new System.IO

我正在使用Selenium为我的网站做一些自动测试。如果某个网站或某个网站中的某个页面关闭,我需要将错误代码和说明保存在文件中。 我成功地使用了StatusCode和StatusDescription,但它们都给了我相同的模糊输出。对于ex,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 (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();
        }

你好,你有没有修改密码?