首页 文章

从WebClient获取HTTP 302重定向的位置?

提问于
浏览
27

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

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

有没有办法制作一个简单的HTTP请求并返回目标位置而不使用WebClient?

我很想做原始套接字通信,因为HTTP很简单,但网站使用HTTPS,我不想做握手 .

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

4 回答

  • 21

    这很容易做到

    假设您已经创建了一个名为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就在我面前,但我过去曾用过这个来检查重定向 .

  • 17

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

  • 0

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

  • 14

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

相关问题