.NET: Check URL's response status code?

后端 未结 5 2194
时光说笑
时光说笑 2021-02-18 18:36

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 possi

5条回答
  •  清酒与你
    2021-02-18 19:04

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

提交回复
热议问题