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

发布于 2024-08-28 04:31:48 字数 283 浏览 3 评论 0原文

我有一个返回 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 技术交流群。

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

发布评论

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

评论(4

绅刃 2024-09-04 04:31:48

这很容易做到

让我们假设您已经创建了一个名为 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,但我过去曾使用它来检查重定向。

It's pretty easy to do

Let's assume you've created an HttpWebRequest called myRequest

// 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
}

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.

剧终人散尽 2024-09-04 04:31:48

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

On HttpWebRequest you can set AllowAutoRedirect to false to handle the redirect yourself.

各自安好 2024-09-04 04:31:48

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

The HttpWebRequest has a property AllowAutoRedirect which you can set to false (it is always true for WebClient), and then get the Location HTTP header.

萌酱 2024-09-04 04:31:48

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

Also, for someone who just needs the new location, HttpResponseMessage has a RequestMessage property. Sometimes it can be useful, because WebClient doesn't support changing the AllowAutoRedirect property once it's been set.

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