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

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

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

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

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

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

HttpWebRequest您可以将AllowAutoRedirect设置为falseAllowAutoRedirect处理重定向。

这很容易做到

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

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

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