如何通过Net.WebRequest正确发送JSON数据-PowerShell [英] How to correctly send json data via Net.WebRequest - PowerShell
问题描述
我正在使用Powershell脚本将JSON数据发布到REST接口,并且每次都收到(400)错误请求.我对此并不陌生,也不清楚我是否/应该如何编码数据.我知道我需要将contenttype设置为application/json,但是我使用的编码选择是什么导致了我的问题,如果是的话,我应该使用什么?
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()
推荐答案
在$requestStream.Write()
之后放入$requestStream.Close()
以查看是否会将数据刷新到服务器.
After the $requestStream.Write()
put in a $requestStream.Close()
to see if that will flush the data to the server.
这篇关于如何通过Net.WebRequest正确发送JSON数据-PowerShell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!