我试图弄清楚网页返回的状态码,根据Linux子系统上curl的结果,它肯定是301(永久重定向),但是在PowerShell中使用curl或WebRequest对象时,它返回200(OK)。
为什么会这样呢?
我试图弄清楚网页返回的状态码,根据Linux子系统上curl的结果,它肯定是301(永久重定向),但是在PowerShell中使用curl或WebRequest对象时,它返回200(OK)。
为什么会这样呢?
这是因为.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
-MaximumRedirection 0
的 curl 别名会导致错误。添加-ErrorAction Ignore
以实际查看响应。 - Dan-MaximumRedirection 0
开关将显示重定向响应以及“已超过最大重定向计数”的消息。 - Dan