我试图从网页中获取结果并避免网络异常我想在请求流的结果之前检查状态代码。但是:
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
在我尝试使用后尝试获取错误代码时抛出异常
response.StatusCode
有没有办法避免异常才能获得StatusCode
?
答案 0 :(得分:0)
只有在调用GetResponse()方法后才能请求StatusCode。您需要在try / catch块中包装GetResponse()。看看Check if a url is reachable - Help in optimizing a Class。
如果您只想测试服务器可访问性,那么您可以使用Ping。
答案 1 :(得分: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 output in real time刚刚改变了一点]
用法如:
MessageBox.Show(ExecuteCommandSync("ping www.stackoverflow.com"));