【问题标题】:Getting the location from a WebClient on a HTTP 302 Redirect?通过 HTTP 302 重定向从 WebClient 获取位置?
【发布时间】:2010-04-08 22:15:52
【问题描述】:

我有一个返回 HTTP 302 重定向的 URL,我想获取它重定向到的 URL。

问题是 System.Net.WebClient 似乎实际上遵循它,这很糟糕。 HttpWebRequest 似乎也是如此。

有没有办法在没有 WebClient 跟随的情况下发出简单的 HTTP 请求并取回目标位置?

我很想进行原始套接字通信,因为 HTTP 很简单,但该站点使用 HTTPS,我不想进行握手。

最后,我不在乎我使用哪个类,我只是不希望它遵循 HTTP 302 重定向:)

【问题讨论】:

    标签: c# .net http sockets https


    【解决方案1】:

    这很容易做到

    假设您创建了一个名为 myRequest 的 HttpWebRequest

    // don't allow redirects, they are allowed by default so we're going to override
    myRequest.AllowAutoRedirect = false;
    
    // send the request
    HttpWebResponse response = myRequest.GetResponse();
    
    // check the header for a Location value
    if( response.Headers["Location"] == null )
    {
      // null means no redirect
    }
    else
    {
      // anything non null means we got a redirect
    }
    

    请原谅我面前没有 VS 的任何编译错误,但我过去曾使用它来检查重定向。

    【讨论】:

    • 添加了允许重定向为假,因为这是原始 OP 的一部分。
    • 错字:AllowAutoRedirect 不是AutoAllowRedirect
    【解决方案2】:

    HttpWebRequest 上,您可以将AllowAutoRedirect 设置为false 以自行处理重定向。

    【讨论】:

      【解决方案3】:

      HttpWebRequest 有一个属性AllowAutoRedirect,您可以将其设置为 false (it is always true for WebClient),然后获取Location HTTP 标头。

      【讨论】:

      【解决方案4】:

      此外,对于只需要新位置的人,HttpResponseMessage 有一个 RequestMessage 属性。有时它可能很有用,因为 WebClient 不支持在设置后更改 AllowAutoRedirect 属性。

      【讨论】:

        猜你喜欢
        • 2011-12-05
        • 2012-08-18
        • 1970-01-01
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        • 2014-01-09
        • 1970-01-01
        • 2016-06-30
        相关资源
        最近更新 更多