powershell - 如何在 powershell 2.0 上使用 POST 方法传递 JSON 参数?
问题描述
我有一个在 powershell 版本 3 中运行良好的 Powershell 代码。
我也需要在 powershell 2.0 中运行此代码。但是 PS 2.0 版不支持 Invoke-WebRequest。
请帮我!
$params = "metrics[]=failed:count"
$failed = (Invoke-WebRequest -Uri http://localhost:9000/stats -Method POST -Body $params -ContentType "application/json").Content
$x = $failed | ConvertFrom-Json
解决方案
未经测试,但我认为这可能会有所帮助:
$params = "metrics[]=failed:count"
$result = @{}
try{
$request = [System.Net.WebRequest]::Create('http://localhost:9000/stats')
$request.Method = 'POST'
$request.ContentType = 'application/json'
$request.Accept = "application/json"
$body = [byte[]][char[]]$params
$upload = $request.GetRequestStream()
$upload.Write($body, 0, $body.Length)
$upload.Flush()
$upload.Close()
$response = $request.GetResponse()
$stream = $response.GetResponseStream()
$streamReader = [System.IO.StreamReader]($stream)
$result['StatusCode'] = $response.StatusCode
$result['StatusDescription'] = $response.StatusDescription
$result['Content'] = $streamReader.ReadToEnd()
$streamReader.Close()
$response.Close()
}
catch{
throw
}
# I suggest checking $result.StatusCode here first..
$x = $result.Content | ConvertFrom-Json
推荐阅读
- c# - DateTime.Parse 的 FormatException。检查我的日期字符串中的哪个部分有误
- mercurial - 推送后如何自动将远程 mercurial 存储库保持在提示状态
- sql-server - SQL 在 where 子句中使用 CASE
- node.js - MERN 堆栈,REST api Postman,无法获取 /
- android - 如何在 Activity 及其父级中添加 DI (Dagger 2)
- ms-access - 从启动时以低优先级模式运行 Access
- firebase - 具有分析和用户属性的 Firebase 云消息
- ios - 检查没有 Alamofire 的响应状态
- c# - 为什么将带有子对象列表的模型传递给控制器时,子对象列表不会被传递?
- java - Java:如何用 1 个字符串查找/替换(不区分大小写)几个子字符串?