55

When sending the GET request to the server, which uses self-signed 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
$RESPONSE=Invoke-WebRequest -Uri https://yadayada:8080/bla -Method GET
echo $RESPONSE

I'm getting following Response:

StatusCode        : 200
StatusDescription : OK
Content           : {123, 10, 108, 111...}
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 21
                    Date: Sat, 11 Jun 2016 10:11:03 GMT

                    {
                        flag:false
                    }
Headers           : {[Content-Length, 21], [Date, Sat, 11 Jun 2016 10:11:03 GMT]}
RawContentLength  : 21

Content contains some wired numbers, so I went after RawContent, how would I parse the JSON inside, ignoring headers? or is there a clean way to get Content from those numbers?

user52028778
  • 27,164
  • 3
  • 36
  • 42
  • 2
    Do yiou need the JSON at all or just the values? You could replace `Invoke-WebRequest` with `Invoke-RestMethod` which auto-converts json response to a `psobject` so you can use `$response = Intoke-RestMethod -Uri "https://yadayada:8080/bla"; $response.flag` – Frode F. Jun 11 '16 at 11:32
  • 1
    Thanks Frode F., this solves my puzzle. For me JSON values are good enough, if you would repost this as answer I'll accept it – user52028778 Jun 11 '16 at 11:44

3 Answers3

115

You could replace Invoke-WebRequest with Invoke-RestMethod which auto-converts json response to a psobject so you can use:

$response = Invoke-RestMethod -Uri "https://yadayada:8080/bla"
$response.flag 
user52028778
  • 27,164
  • 3
  • 36
  • 42
Frode F.
  • 52,376
  • 9
  • 98
  • 114
25

If you have a need to use Invoke-WebRequest over Invoke-RestMethod you can convert it to an object by turning it into a string first

$response = Invoke-WebRequest -Uri "https://yadayada:8080/bla"
$jsonObj = ConvertFrom-Json $([String]::new($response.Content))
  • 3
    Heads up in case it helps anyone else - the syntax on line 2 in this answer doesn't work for Powershell v4 - but Invoke-RestMethod did work. Invoke-RestMethod also has a benefit (in Powershell v4 at least) to not have a dependency on IE - to get Invoke-WebRequest to work on an environment without IE available, I had to provide -UseBasicParsing. – David E Nov 15 '19 at 10:50
6

This way:

$response = Invoke-WebRequest -Uri <your_uri>
if ($response.statuscode -eq '200') {
    $keyValue= ConvertFrom-Json $response.Content | Select-Object -expand "<your_key_name>"
}
aalbagarcia
  • 1,019
  • 7
  • 20
jiboj
  • 61
  • 1
  • 1