我如何检查302响应?的WebRequest

时间:2009-09-08 00:05:23

标签: .net httpresponse http-status-code-302

使用WebRequest我想知道我是否得到了

  

“302暂时移动”

响应而不是自动获取新网址。

3 个答案:

答案 0 :(得分:32)

如果您想检测重定向响应,而不是自动创建WebRequest,并将AllowAutoRedirect属性设置为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"];
}

答案 1 :(得分:3)

像这样:

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

代码应为

HttpStatusCode.TemporaryRedirect

答案 2 :(得分:1)

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