我如何检查一个302回应? 的WebRequest(How do i check for a 3

2019-07-05 12:56发布

使用WebRequest我想知道如果我得到一个

“302暂时移动”

响应而不是自动获得新的URL。

Answer 1:

如果要检测,而不是跟随它自动创建一个重定向响应, 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"];
}


Answer 2:

像这样:

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

该代码应该是

HttpStatusCode.TemporaryRedirect


Answer 3:

VB .NET代码

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


文章来源: How do i check for a 302 response? WebRequest