0

我正在尝试从网页中获取结果并避免网络异常,我想在从流中请求结果之前检查状态代码。然而:

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

当我尝试在此使用后获取错误代码时引发异常 response.StatusCode

有没有办法避免异常获得StatusCode

4

2 回答 2

0

只有在调用 GetResponse() 方法后,您才能请求 StatusCode。您需要将 GetResponse() 包装在 try/catch 块中。查看Check if a url is reachable - Help in optimization a Class

如果您只想测试服务器的可达性,那么您可以使用 Ping。

于 2012-10-25T08:59:26.267 回答
0

您可以使用 Ping 从网站获取更多统计信息。(它有点慢,大约需要 1-3 秒左右)

public string ExecuteCommandSync(object command)
    {
        try
        {
            // create the ProcessStartInfo using "cmd" as the program to be run,
            // and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows,
            // and then exit.
            var procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);


            // The following commands are needed to redirect the standard output.
            // This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            var proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            return proc.StandardOutput.ReadToEnd();
        }
        catch (Exception objException)
        {
            Console.WriteLine("Error: " + objException.Message);
            return "";
            // Log the exception
        }
    }

[来自:C# cmd 实时输出 只是稍微改了一下]

用法如:

MessageBox.Show(ExecuteCommandSync("ping www.stackoverflow.com"));
于 2012-10-25T09:02:50.267 回答