【问题标题】:powershell curl and WebRequest both follow redirectspowershell curl 和 WebRequest 都遵循重定向
【发布时间】:2016-12-15 04:30:18
【问题描述】:

根据Linux子系统上的curl,我试图找出我的网页返回的状态码,最肯定是301(永久移动),但是使用curl或powershell上的WebRequest对象,它返回200(OK )。

这是为什么?

【问题讨论】:

    标签: powershell curl webrequest


    【解决方案1】:

    这是因为 .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 cmdlet:

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

    或者,使用 -L 标志在 curl 中跟踪重定向:

    curl -L google.com
    

    【讨论】:

    • PowerShell 的 curl 别名使用 -MaximumRedirection 0 会导致错误。添加-ErrorAction Ignore 以实际查看响应。
    • @Dan 您使用的是什么版本的 PowerShell?我的机器有 5.1.17134.407,它没有抛出任何错误。
    • @Franklin,我目前使用的是同一版本,现在-MaximumRedirection 0 开关将显示重定向响应以及“已超出最大重定向计数”消息。
    • 请注意 this will not help in PowerShell 6.0(又名 PowerShell 核心)。
    • 谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2015-03-01
    • 2011-03-11
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多