PowerShell的curl和WebRequest都会遵循重定向。

16

我试图弄清楚网页返回的状态码,根据Linux子系统上curl的结果,它肯定是301(永久重定向),但是在PowerShell中使用curl或WebRequest对象时,它返回200(OK)。

为什么会这样呢?

1个回答

28

这是因为.NET和PowerShell默认遵循重定向,但curl不会这样做。HttpWebRequest.AllowAutoRedirect的默认值为true,而Invoke-WebRequest的MaximumRedirection默认值为5。

要通过WebRequest关闭自动重定向:

$request = [System.Net.WebRequest]::Create("http://google.com")
$request.AllowAutoRedirect = $false
$request.GetResponse()

或使用 Invoke-WebRequest 命令:

Invoke-WebRequest -Uri "http://google.com" -MaximumRedirection 0

或者,使用curl中的-L标志来跟随重定向:

curl -L google.com

9
PowerShell 中使用 -MaximumRedirection 0 的 curl 别名会导致错误。添加 -ErrorAction Ignore 以实际查看响应。 - Dan
1
@Dan 你使用的PowerShell版本是什么?我的机器上安装的是5.1.17134.407,没有出现任何错误。 - Franklin Yu
@Franklin,我目前正在使用相同的版本,现在-MaximumRedirection 0开关将显示重定向响应以及“已超过最大重定向计数”的消息。 - Dan
"Invoke-WebRequest http://minnesota.publicradio.org/tools/podcasts/song_of_the_day.xml -MaximumRedirection 8 -Verbose" 对我来说无法像 "curl -vL http://minnesota.publicradio.org/tools/podcasts/song_of_the_day.xml" 那样重定向。 - brianary
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接