代码之家  ›  专栏  ›  技术社区  ›  GollyJer

如何发布到维生素列表.com的API通过Powershell?

  •  0
  • GollyJer  · 技术社区  · 14 年前

    Vitalist API文档 here .
    我在Powershell中尝试了HttpWebResponse,但缺少了一些内容。如有任何提示,我们将不胜感激。

    谢谢。

    1 回复  |  直到 14 年前
        1
  •  3
  •   stej    14 年前

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

    如果传递一些数据,请按如下方式对其进行编码:

    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)
    
    推荐文章