如何检查 302 响应?网络请求

发布于 2024-08-03 16:19:07 字数 116 浏览 4 评论 0原文

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

“302暂时移动”

响应而不是自动获取新的 url。

Using WebRequest I want to know if I get a

"302 Moved Temporarily"

response instead of automatically get the new url.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无远思近则忧 2024-08-10 16:19:07

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

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"];
}
最初的梦 2024-08-10 16:19:07

像这样:

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

代码应该是

HttpStatusCode.TemporaryRedirect

Like so:

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

The code should be

HttpStatusCode.TemporaryRedirect
空城仅有旧梦在 2024-08-10 16:19:07

VB网络代码

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文