0

我想使用 Powershell 向我的 Vitalist.com 帐户发布新操作。Vitalist API 文档在这里
我已经在 Powershell 中尝试过 HttpWebResponse,但我遗漏了一些东西。任何指针表示赞赏。

谢谢。

4

1 回答 1

3

我对 Vitalis 一无所知,但要执行 HTTP POST,您可以使用此函数:

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();
  }
}

如果您传递一些数据,请像这样对它们进行 urlencode:

add-type -AssemblyName System.Web
[system.Web.Httputility]::UrlEncode($data)

只是一个猜测 - 也许这样的事情可以工作?

$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)
于 2010-02-18T12:56:34.413 回答