PowerShell Invoke-WebRequest 抛出 WebCmdletResponseException

问题描述 投票:0回答:1

执行行

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个回答
12
投票

这是因为

Invoke-WebRequest
在底层使用了
HttpWebRequest
,除了最新版本的 .Net 之外的所有版本都默认使用 SSLv3 和 TLSv1。

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

[System.Net.ServicePointManager]::SecurityProtocol

您要连接的网站仅支持 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
}
© www.soinside.com 2019 - 2024. All rights reserved.