【问题标题】:PowerShell Invoke-WebRequest throws WebCmdletResponseExceptionPowerShell Invoke-WebRequest 引发 WebCmdletResponseException
【发布时间】:2018-02-03 23:36:05
【问题描述】:

执行Invoke-WebRequest -Uri https://www.freehaven.net/anonbib/date.html 行时,PowerShell 会抛出WebCmdletResponseException。我怎样才能获得有关它的更多信息,以及可能导致这种情况的原因是什么?虽然我可以使用 Python 成功获取页面的内容,但在 PowerShell 中它会引发异常。

完全例外:

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-WebRequest -Uri https://www.freehaven.net/anonbib/date.html
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

【问题讨论】:

    标签: powershell ssl httpwebrequest tls1.2 servicepointmanager


    【解决方案1】:

    这是因为 Invoke-WebRequest 在后台使用 HttpWebRequest,除了最新版本的 .Net 之外,其他所有版本都默认使用 SSLv3 和 TLSv1。

    您可以通过查看当前值来看到这一点:

    [System.Net.ServicePointManager]::SecurityProtocol
    

    site you're connecting to only supports TLS 1.2

    您可以更改允许的协议,但它会在您的应用程序运行期间全局应用:

    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
    

    这会覆盖值。

    当然,这会破坏您的应用程序中依赖与不支持 TLS 1.2 的服务器的连接的任何其他内容

    一种安全的方法可能是添加 TLS 1.2:

    [System.Net.ServicePointManager]::SecurityProtocol] = (
        [System.Net.ServicePointManager]::SecurityProtocol -bor 
        [System.Net.SecurityProtocolType]::Tls12
    )
    
    # parentheses are for readability
    

    如果这仍然会导致其他站点出现问题(不确定是什么,也许是一个说它接受 TLS 1.2 但它的实现被破坏而它的 TLS 1.0 工作正常的站点?),你可以保存以前的值并恢复它。

    $cur = [System.Net.ServicePointManager]::SecurityProtocol]
    try {
        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
        Invoke-WebRequest -Uri https://www.freehaven.net/anonbib/date.html
    } finally {
        [System.Net.ServicePointManager]::SecurityProtocol = $cur
    }
    

    【讨论】:

    • 我遇到了同样的错误(底层连接已关闭)并使用了您上面提到的解决方案,但不幸的是,它现在抛出了类似“Invoke-RestMethod:远程服务器返回错误: (503) 服务器不可用。”你知道有什么解决办法吗?
    • @Abhi 听起来这是一个单独的问题。连接关闭意味着它不支持 TLS 1.0。如果您仍然遇到 TLS 问题,则连接将在您收到 HTTP 状态代码 503 之前关闭,因此您的 TLS 问题似乎已解决。但是任何 500 级错误都可能是网站所有者的责任,而不是客户的责任,所以我认为你必须与他们核实。
    • 你是对的!这是服务器上的一个问题,它不可用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2021-07-22
    • 2012-07-26
    • 2021-10-19
    相关资源
    最近更新 更多