Jobbo
Jobbo

Reputation: 1418

How to POST JSON from Powershell to a PHP script

I'm trying to send a JSON object to a PHP script with Powershell, and have that PHP script simply return what it gets as JSON...

In Powershell I'm doing this:

$a = New-Object System.Collections.ArrayList;
$a.Add(@{
    'prop1' = 'something'
    'prop2' = 'something else'
});

$a.Add(@{
    'prop1' = 'green'
    'prop2' = 'blue'
});

$b = New-Object System.Collections.ArrayList;
$b.Add(@{
    'prop1' = 'another'
    'prop2' = 'yet another'
});

$b.Add(@{
    'prop1' = 'red'
    'prop2' = 'black'
});


$json = @{
    'first' = $a
    'second' = $b
} | ConvertTo-Json;

$json

At which point $json is a String like this:

{
    "second":  [
                   {
                       "prop2":  "yet another",
                       "prop1":  "another"
                   },
                   {
                       "prop2":  "black",
                       "prop1":  "red"
                   }
               ],
    "first":  [
                  {
                      "prop2":  "something else",
                      "prop1":  "something"
                  },
                  {
                      "prop2":  "blue",
                      "prop1":  "green"
                  }
              ]
}

Then I POST a Invoke-WebRequest with $json as the body:

(Invoke-WebRequest -Uri $url -ContentType 'application/json' -Method Post -Body $json).Content;

The target is this PHP5 script:

<?php
header('Content-Type:application/json');
echo json_encode(array("POST" => $_POST, "GET" => $_GET));
?>

But the response is just empty:

{"POST":[],"GET":[]}

I've tried getting PHP to just echo back a static string, which works fine, but can you see anything wrong with how I'm POSTing/accepting/responding here? I'm stumped

Upvotes: 1

Views: 1566

Answers (1)

Jobbo
Jobbo

Reputation: 1418

I answered my own question.

The Powershell side was eventually:

$json = @{
    'a' = $a
    'b' = $b
} | ConvertTo-Json -Compress

$web = Invoke-WebRequest -Uri $url -Method Post -Body $json -ContentType 'application/json; charset=UTF-8' 

So $a and $b are both arrays of custom objects as in my original question, and $json is a Hashtable that becomes a string via ConvertTo-Json

When using Invoke-Webrequest with -ContentType 'application/json' PHP doesn't receive a populated $_POST array. I had to read in the raw input in my php script like this:

<?php
header('Content-Type:application/json; charset=UTF-8');
$json = json_decode(file_get_contents("php://input"));
echo json_encode($json, JSON_FORCE_OBJECT);
?>

Then the result of Invoke-WebRequest, $web, has the JSON string as its Content property. Or I could use Invoke-RestMethod instead and the return type is a PSCustomObject

Another problem I overcame was that my real JSON string had special characters, requiring me to add charset=UTF-8

Upvotes: 1

Related Questions