PowerShell Invoke-WebRequest抛出WebCmdletResponseException

时间:2018-02-03 23:36:05

标签: powershell ssl httpwebrequest tls1.2 servicepointmanager

执行第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

1 个答案:

答案 0 :(得分:4)

这是因为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
}
相关问题