views:

106

answers:

1

I am working on a powershell script to post json data to a REST interface and am getting (400) Bad Request on each time. I am new to this, and am unclear as to if/how I should be encoding the data. I know I need to set the contenttype to application/json, but is the encoding choice I am using what is causing my problem, and if so what should I be using?

$cred = New-Object System.Net.NetworkCredential -ArgumentList $authUser,$authPass
$url = 'http://localhost:8080/alfresco/service/api/people'
$request = [Net.WebRequest]::Create($url)

$request.ServicePoint.Expect100Continue = $false

$request.Credentials = $cred
$request.ContentType = "application/json"
$request.Method = "POST"

$data = (New-Object PSObject |
    Add-Member -PassThru NoteProperty username $username |
    Add-Member -PassThru NoteProperty firstName $firstname |
    Add-Member -PassThru NoteProperty lastName $lastname |
    Add-Member -PassThru NoteProperty email $email |
    Add-Member -PassThru NoteProperty password $password
) | ConvertTo-JSON

$bytes = [System.Text.Encoding]::ASCII.GetBytes($data)

$request.ContentLength = $bytes.Length

$requestStream = [System.IO.Stream]$request.GetRequestStream()
$requestStream.write($bytes, 0, $bytes.Length)

$response = $request.GetResponse()
A: 

After the $requestStream.Write() put in a $requestStream.Close() to see if that will flush the data to the server.

Keith Hill
Both with and without that $requestStream.Close() I get the following error:Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (400) Bad Request."At :line:56 char:34+ $response = $request.GetResponse <<<< () That is what has led me to believe it had something to do with the encoding, but I could be completely wrong.
Kris
Can you post the output of the call to ConvertTo-Json to ensure you're sending valdi JSON?
Keith Hill
the data variable output is this{ "email": "[email protected]", "firstName": "Kris", "lastName": "Test", "password": "test123", "username": "kristest" }
Kris
A little more information: I changed the [System.Text.Encoding] to UTF8, and I am now getting an error from System.Byte[]Cannot convert argument "0", with value: "{ "email": "[email protected]", "firstName": "Kris", "lastName": "Test", "organisation": "test123", "username": "kristest" }", for "GetChars" to type "System.Byte[]"
Kris
More errors: Error: "Input string was not in a correct format."""At :line:48 char:48+ $bytes = [System.Text.Encoding]::UTF8.GetChars <<<< ($data)
Kris
Yeah, I would revert back to using ASCII encoding. One approach to debugging this is to go grab Fiddler and use it to observe the request and the response headers. Perhaps there is more info in the response headers. Also you might try turning off authentication temporarily just to see if the problem lies with authentication (AuthenticationLevel or PreAuthenticate).
Keith Hill