How do i check for a 302 response? WebRequest

余生长醉 提交于 2019-11-27 21:19:52
devstuff

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

Like so:

HttpWebResponse response;
int code = (int) response.StatusCode;

The code should be

HttpStatusCode.TemporaryRedirect
Zibri

VB Net Code

Function GetRealUrl(someUrl As String) As String
        Dim req As HttpWebRequest = TryCast(WebRequest.Create(someUrl), HttpWebRequest)
        req.AllowAutoRedirect = False
        Dim response As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
        If response.StatusCode = HttpStatusCode.Redirect OrElse response.StatusCode = HttpStatusCode.MovedPermanently Then
            ' Do something...
            Dim newUrl As String = response.Headers("Location")
            getrealurl = newUrl
        Else
            getrealurl = someUrl
        End If
End Function
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!