.NET:检查URL响应状态代码?

时间:2010-09-10 23:12:22

标签: c# .net http

在.NET中检查Web服务器回复GET请求的状态代码的最简单方法是什么?

请注意,我不需要响应的正文。实际上,如果可能的话,只应该请求标题。然而,话虽如此,如果要求省略响应的主体会显着增加代码的复杂性,接收正文就可以了。

另外,我特别感兴趣的是捕获所有可能的适当的异常(System.Net.WebException,System.IO.IOException,System.Net.Sockets.SocketException等),这个例程每天会运行数千次。

5 个答案:

答案 0 :(得分:26)

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;
    }

答案 1 :(得分:12)

使用HTTP方法HEAD,它与GET相同,但不返回正文:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.Method = "HEAD";
var response = (HttpWebResponse)request.GetResponse();

// status code...
response.StatusCode;

来自Section 9.4 of RFC2616

  

HEAD方法与GET相同   除了服务器不能返回   响应中的消息正文。该   HTTP中包含的元信息   响应HEAD请求的标头   应该与信息完全相同   发送以响应GET请求。   该方法可用于获得   关于实体的元信息   没有提出要求所暗示的   转移实体 - 身体本身。   此方法通常用于测试   有效性的超文本链接,   可访问性,最近   修改

答案 2 :(得分:6)

我最终采用了这种方法,结合了IvanFerić的答案和适当的特殊案例支持:

public async Task<bool> IsAccessibleAsync (string url)
{
    if (url == null)
        throw new ArgumentNullException ("url");

    if (url.IndexOf (':') < 0)
        url = "http://" + url.TrimStart ('/');

    if (!Uri.IsWellFormedUriString (url, UriKind.Absolute))
        return false;

    var request = (HttpWebRequest) WebRequest.Create (url);
    request.Method = "HEAD";

    try
    {
        using (var response = await request.GetResponseAsync () as HttpWebResponse)
        {
            if (response != null && response.StatusCode == HttpStatusCode.OK)
                return true;

            return false;
        }
    }
    catch (WebException)
    {
        return false;
    }
}

答案 3 :(得分:3)

如果你使用HttpWebRequest,那很简单:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://url");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode status = response.StatusCode;

您可以使用全局catch子句包围它,或查看WebRequest.Create和.GetResponse的文档以查看将抛出的异常。

答案 4 :(得分:1)

这是我想出的处理404异常的方法。下面还有一个测试。

public static HttpStatusCode GetUrlStatus(string url, string userAgent)
{
    HttpStatusCode result = default(HttpStatusCode);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.UserAgent = userAgent;
    request.Method = "HEAD";

    try
    {
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            if (response != null)
            {
                result = response.StatusCode;
                response.Close();
            }
        }
    }
    catch (WebException we)
    {
        result = ((HttpWebResponse)we.Response).StatusCode;
    }

    return result;
}


[Test]
public void PageNotFoundShouldReturn404()
{
    //Arrange
    HttpStatusCode expected = HttpStatusCode.NotFound;
    string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";

    //Act
    HttpStatusCode result = WebHelper.GetUrlStatus("http://www.kellermansoftware.com/SomePageThatDoesNotExist", userAgent);

    //Assert
    Assert.AreEqual(expected, result);
}