views:

172

answers:

1

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 appreciated.

Thanks.

A: 

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)
stej
stej. Thanks for the help but I can't get it working. I get this error: Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (401) Unauthorized." but I know I'm feeding it the correct credentials. Weird.
GollyJer