2010-02-18 32 views
0

我希望使用Powershell向我的Vitalist.com帳戶發佈新操作。 Vitalist API文檔是here
我試過Powershell中的HttpWebResponse,但我錯過了一些東西。任何指針讚賞。如何通過Powershell發佈到Vitalist.com的API?

謝謝。

+0

我很想看到這個問題的更一般的版本與stej的優秀答案。 – 2011-02-09 19:53:33

回答

3

我不知道維塔利斯什麼,但執行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) 
+0

stej。感謝您的幫助,但我無法得到它的工作。我得到這個錯誤:使用「0」參數調用「GetResponse」異常:「遠程服務器返回一個錯誤:(401)未經授權。」但我知道我正在爲它提供正確的憑據。奇怪的。 – GollyJer 2010-02-21 08:02:43