Invoke-RestMethod Issues

This topic contains 4 replies, has 1 voice, and was last updated by  Arun _Kumar 2 years, 2 months ago.

  • Author
  • #37241

    Arun _Kumar

    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?

  • #37243

    Arun _Kumar

    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"

  • #37244

    Arun _Kumar

    I am using following powershell version:

    PS C:\> $PSVersionTable.PSVersion

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

  • #37245

    Arun _Kumar

    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

  • #37478

    Arun _Kumar

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

You must be logged in to reply to this topic.