.NET:检查URL的响应状态code? [英] .NET: Check URL's response status code?

查看:198
本文介绍了.NET:检查URL的响应状态code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是.NET中最简单的方法来检查与一个GET请求codeA的Web服务器回复什么样的地位?

请注意,我不需要响应的正文。实际上,如果可能的话,只有标题应该要​​求。话虽如此,但是,如果请求的响应人体显著省略增加的code的复杂性,接受身体就可以了。

另外,我在追赶所有可能的适当的例外(System.Net.WebException,System.IO.IOException,System.Net.Sockets.SocketException等)特别感兴趣,因为这个程序将运行数千次。

解决方案

 公开的HTTPStatus code GetHeaders(字符串URL)
    {
        的HTTPStatus code结果=默认(的HTTPStatus code);

        VAR请求= HttpWebRequest.Create(URL);
        request.Method =HEAD;
        使用(VAR响应= request.GetResponse()作为HttpWebResponse)
        {
            如果(响应!= NULL)
            {
                结果= response.Status code;
                response.Close();
            }
        }

        返回结果;
    }
 

What's the easiest way in .NET to check what status code a web server replies with to a GET request?

Note that I do not need the body of the response. In fact, if possible, only the header should be requested. Having said that, however, if requesting that the body of the response be omitted significantly increases the complexity of the code, receiving the body would be fine.

Also, I'm particularly interested in catching ALL the possible appropriate exceptions (System.Net.WebException, System.IO.IOException, System.Net.Sockets.SocketException, etc.), as this routine will run thousands of times a day.

解决方案

public HttpStatusCode GetHeaders(string url)
    {
        HttpStatusCode result = default(HttpStatusCode);

        var request = HttpWebRequest.Create(url);
        request.Method = "HEAD";
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            if (response != null)
            {
                result = response.StatusCode;
                response.Close();
            }
        }

        return result;
    }

这篇关于.NET:检查URL的响应状态code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆