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

两盒软妹~` 提交于 2021-02-08 03:43:20

问题


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()

回答1:


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



来源:https://stackoverflow.com/questions/3535218/how-to-correctly-send-json-data-via-net-webrequest-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!