如何通过Net.WebRequest正确发送json数据 - PowerShell

时间:2010-08-20 22:07:39

标签: .net json rest powershell

我正在使用powershell脚本将json数据发布到REST接口,并且每次都会收到(400)错误请求。我是新手,并不清楚我是否应该/如何编码数据。我知道我需要将contenttype设置为application / json,但是我正在使用导致我的问题的编码选择,如果是这样我应该使用什么?

$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 个答案:

答案 0 :(得分:1)

$requestStream.Write()放入$requestStream.Close()后查看是否会将数据刷新到服务器。