首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >网页的状态码

网页的状态码
EN

Stack Overflow用户
提问于 2012-10-25 16:51:45
回答 2查看 87关注 0票数 0

我正在尝试从网页中获取结果,并且为了避免web异常,我想在从流中请求结果之前检查状态代码。但是:

代码语言:javascript
复制
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

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

有没有一种方法可以避免异常来获取StatusCode

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-25 16:59:26

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

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

票数 0
EN

Stack Overflow用户

发布于 2012-10-25 17:02:50

您可以使用Ping从该站点获取更多统计数据。(虽然有点慢,但需要1-3秒左右)

代码语言:javascript
复制
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 Just From changed ]

用法如下:

代码语言:javascript
复制
MessageBox.Show(ExecuteCommandSync("ping www.stackoverflow.com"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13064943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档