.NET: Check URL's response status code?

后端 未结 5 2188
时光说笑
时光说笑 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:52

    Use the HTTP method HEAD, which is the same as GET except doesn't return the body:

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

    From Section 9.4 of RFC2616:

    The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

提交回复
热议问题