How do i check for a 302 response? WebRequest

前端 未结 3 1997
忘掉有多难
忘掉有多难 2020-12-05 19:26

Using WebRequest I want to know if I get a

\"302 Moved Temporarily\"

response instead of automatically get the new

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 19:54

    If you want to detect a redirect response, instead of following it automatically create the WebRequest and set the AllowAutoRedirect property to false:

    HttpWebRequest request = WebRequest.Create(someUrl) as HttpWebRequest;
    request.AllowAutoRedirect = false;
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    if (response.StatusCode == HttpStatusCode.Redirect || 
        response.StatusCode == HttpStatusCode.MovedPermanently)
    {
        // Do something here...
        string newUrl = response.Headers["Location"];
    }
    

提交回复
热议问题