在我调用WebClient.DownloadString

时间:2017-10-17 17:14:27

标签: powershell

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

E.g:

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说的: enter image description here

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

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

1 个答案:

答案 0 :(得分:0)

因此更多地挖掘错误并在内部异常中找到它:

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上得到解答的想法,你只需要看得足够好。