How to POST to Vitalist.com's API via Powershell?
I'd liketo use Powershell to post a new action to my Vitalist.com account. The Vitalist API documentation is here.
I've tried HttpWebResponse in Powershell but I'm missing something. Any pointers are appre开发者_C百科ciated.Thanks.
I don't know anything about Vitalis, but to execute HTTP POST you can use this function:
function Execute-HttpPost
{
param(
[string] $url = $null,
[string] $data = $null,
[System.Net.NetworkCredential]$credentials = $null,
[string] $contentType = "application/x-www-form-urlencoded",
[string] $codePageName = "UTF-8",
[string] $userAgent = $null
);
if ($url -and $data)
{
[System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($url);
$webRequest.ServicePoint.Expect100Continue = $false;
if ( $credentials )
{
$webRequest.Credentials = $credentials;
$webRequest.PreAuthenticate = $true;
}
$webRequest.ContentType = $contentType;
$webRequest.Method = "POST";
if ( $userAgent )
{
$webRequest.UserAgent = $userAgent;
}
$enc = [System.Text.Encoding]::GetEncoding($codePageName);
[byte[]]$bytes = $enc.GetBytes($data);
$webRequest.ContentLength = $bytes.Length;
[System.IO.Stream]$reqStream = $webRequest.GetRequestStream();
$reqStream.Write($bytes, 0, $bytes.Length);
$reqStream.Flush();
$resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
$sr.ReadToEnd();
}
}
If you pass some data, urlencode them like this:
add-type -AssemblyName System.Web
[system.Web.Httputility]::UrlEncode($data)
Just a guess - maybe something like this could work?
$d = [system.Web.Httputility]::UrlEncode("<request><actions><action><body>some body</body></action></actions></request>")
Execute-HttpPost -url 'http://www.vitalist.com/services/api/actions.xml' -data $d -credentials (Get-Credential)
精彩评论