【问题标题】:Invoke-WebRequest doesn't work until I call WebClient.DownloadStringInvoke-WebRequest 在我调用 WebClient.DownloadString 之前不起作用
【发布时间】:2018-03-29 11:16:07
【问题描述】:

我正在使用 powershell v5 使用带有自签名证书的 TLS1.2 调用内部 API。当我调用 api 时,我总是得到Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.

例如:

PS> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
PS> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
PS> $url = "https://someinternalserver/blah"
PS> $response = Invoke-WebRequest $url
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1

(我查看了错误对象,但没有发现任何有用的信息。)

但是,如果我使用 WebClient 的实例调用相同的 URL,那么使用 WebClient 的调用 AND 所有后续的 powershell 调用都可以正常工作:

PS> $webClient = New-Object System.Net.WebClient
PS> $str = $webClient.DownloadString($url)
PS> Write-Host $str
body of request
PS> $response = Invoke-WebRequest $url
PS> Write-Host $response.Content
body or request

我不确定发生了什么,但我怀疑它与自签名证书或加密货币有关。以下是 chrome 关于加密的说法:

我之前使用过 powershell 调用带有自签名证书的 API,但从未遇到过此类问题。

解决方案:我想在不首先使用 WebClient 的情况下调用 API。 谢谢。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    于是对错误进行了更多挖掘,并在一个内部异常中发现了这一点:

    There is no Runspace available to run scripts in this thread.
    You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. 
    The script block you attempted to invoke was: $true
    

    这导致我来到这里: Powershell 3.0 Invoke-WebRequest HTTPS Fails on All Requests

    这导致我来到这里: https://stackoverflow.com/a/15841856/6311875

    使用该代码而不是 {$true} 就可以了。

    因此,这进一步强化了这样一种想法,即所有问题都已经在 SO 上得到解答,您只需要仔细观察即可。

    【讨论】:

    • 一段时间后遇到了同样的问题,你真的需要深入挖掘错误。绝对不是痕迹中出现的东西。
    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多