How do i check for a 302 response? WebRequest

2019-01-14 12:25发布

Using WebRequest I want to know if I get a

"302 Moved Temporarily"

response instead of automatically get the new url.

3条回答
劫难
2楼-- · 2019-01-14 12:37

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"];
}
查看更多
成全新的幸福
3楼-- · 2019-01-14 12:44

Like so:

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

The code should be

HttpStatusCode.TemporaryRedirect
查看更多
干净又极端
4楼-- · 2019-01-14 12:47

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
查看更多
登录 后发表回答