【发布时间】:2012-10-25 08:51:44
【问题描述】:
我正在尝试从网页中获取结果并避免网络异常,我想在从流中请求结果之前检查状态代码。然而:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
当我尝试在此使用后获取错误代码时引发异常
response.StatusCode
有没有办法避免异常获取StatusCode?
【问题讨论】:
标签: c#
我正在尝试从网页中获取结果并避免网络异常,我想在从流中请求结果之前检查状态代码。然而:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
当我尝试在此使用后获取错误代码时引发异常
response.StatusCode
有没有办法避免异常获取StatusCode?
【问题讨论】:
标签: c#
只有在调用 GetResponse() 方法后,才能请求状态码。您需要将 GetResponse() 包装在 try/catch 块中。看看Check if a url is reachable - Help in optimizing a Class。
如果您只是想测试服务器的可达性,那么您可以使用 Ping。
【讨论】:
您可以使用 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 output in real time刚刚改了一点]
用法如下:
MessageBox.Show(ExecuteCommandSync("ping www.stackoverflow.com"));
【讨论】: