.NET: Check URL's response status code?

后端 未结 5 2174
时光说笑
时光说笑 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 18:46

    If you use HttpWebRequest, it's pretty easy:

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

    You can surround that with a blanket catch clause, or look at the docs for WebRequest.Create and .GetResponse to see what exceptions will get thrown.

提交回复
热议问题