开发者

How to correctly send json data via Net.WebRequest - PowerShell

开发者 https://www.devze.com 2023-01-13 00:09 出处:网络
I am working on a powershell script to post json data to a REST interface and am getting (400) Bad Req开发者_Python百科uest on each time.I am new to this, and am unclear as to if/how I should be encod

I am working on a powershell script to post json data to a REST interface and am getting (400) Bad Req开发者_Python百科uest 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()


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

0

精彩评论

暂无评论...
验证码 换一张
取 消