Author Posts

April 5, 2016 at 3:56 am

I am trying to connect to an external api website. I don't know details around how REST/JSON works, but I want to use powershell to download a csv file via GET method. I could successfully connect via CURL, but with powershell I cannot, and am exhausted.


curl.exe -v -H "Accept: application/json" -u APIKEY: "https://"


Invoke-RestMethod -Uri 'https://' -Headers @{"AUTHORIZATION"="Basic "} -Method Get

I always receive following error:

the underlying connection was closed an unexpected error occurred on a send and the underlying connection was closed an unexpected error occurred on a receive

I tried using following script for certificate:

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"


still no luck.

Can someone help me understand what I am doing wrong?

April 5, 2016 at 4:04 am

Basic is followed by Base64Encoded API KEY. This is what I see when I use the API Web, the one website provides:

"Accept": "application/json",
"Authorization": "Basic Base64Encode",
"Content-Length": 0,
"x-forwarded-for": "3 IP Addresses Separated by Comma"

April 5, 2016 at 4:07 am

I am using following powershell version:

PS C:\> $PSVersionTable.PSVersion

Major Minor Build Revision
—– —– —– ——–
3 0 -1 -1

April 5, 2016 at 4:26 am

I upgraded to v4

PS C:\> $PSVersionTable.PSVersion

Major Minor Build Revision
—– —– —– ——–
4 0 -1 -1

and also used:

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

since TLS1.2 is the requirement, still same error:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.
At line:1 char:1
+ Invoke-RestMethod -Method Get -Uri 'https:////// ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], We
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

If I don't use https, then it says:

Unable to connect to the remote server

April 9, 2016 at 5:44 pm

I moved to 2012 R2 server, and the issues resolved.