通过 HTTP 302 重定向从 WebClient 获取位置?
我有一个返回 HTTP 302 重定向的 URL,我想获取它重定向到的 URL。
问题是 System.Net.WebClient 似乎实际上遵循它,这很糟糕。 HttpWebRequest 似乎也做了同样的事情。
有没有一种方法可以发出简单的 HTTP 请求并返回目标位置,而无需 WebClient 跟随它?
我很想进行原始套接字通信,因为 HTTP 足够简单,但该站点使用 HTTPS 并且我不想进行握手。
最后,我不在乎使用哪个类,我只是不希望它遵循 HTTP 302 重定向:)
I have a URL that returns a HTTP 302 redirect, and I would like to get the URL it redirects to.
The problem is that System.Net.WebClient seems to actually follow it, which is bad. HttpWebRequest seems to do the same.
Is there a way to make a simple HTTP Request and get back the target Location without the WebClient following it?
I'm tempted to do raw socket communication as HTTP is simple enough, but the site uses HTTPS and I don't want to do the Handshaking.
At the end, I don't care which class I use, I just don't want it to follow HTTP 302 Redirects :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这很容易做到
让我们假设您已经创建了一个名为 myRequest 的 HttpWebRequest ,
请原谅任何编译错误我面前没有 VS,但我过去曾使用它来检查重定向。
It's pretty easy to do
Let's assume you've created an HttpWebRequest called myRequest
Excuse any compile errors I don't have VS right in front of me, but I've used this in the past to check for redirects.
在
HttpWebRequest
上,您可以将AllowAutoRedirect
设置为false
来自行处理重定向。On
HttpWebRequest
you can setAllowAutoRedirect
tofalse
to handle the redirect yourself.HttpWebRequest
有一个属性AllowAutoRedirect
您可以将其设置为 false (对于WebClient
始终如此),然后获取位置
HTTP 标头。The
HttpWebRequest
has a propertyAllowAutoRedirect
which you can set to false (it is always true forWebClient
), and then get theLocation
HTTP header.此外,对于只需要新位置的人,
HttpResponseMessage
有一个RequestMessage
属性。有时它可能很有用,因为WebClient
不支持在设置AllowAutoRedirect
属性后对其进行更改。Also, for someone who just needs the new location,
HttpResponseMessage
has aRequestMessage
property. Sometimes it can be useful, becauseWebClient
doesn't support changing theAllowAutoRedirect
property once it's been set.