2016-05-12 52 views
0

我試圖做一個PowerShell相當於這個Python代碼:PowerShell的等效Python的requests.post與數據和文件

import requests 
requests.post('http://someCKANsite/api/action/resource_create', 
       data={"package_id":"my_dataset"}, 
       headers={"X-CKAN-API-Key": "21a47217-6d7b-49c5-88f9-72ebd5a4d4bb"}, 
       files=[('upload', file('/path/to/file/to/upload.csv'))]) 

我曾嘗試:

Invoke-WebRequest -Method Post -Uri http://someCKANsite/api/action/resource_create -Headers $headers -InFile $myfile -Body $rcbody -ContentType "multipart/form-data" 

...包含我的X-CKAN-API-Key$rcbody包含package_id$headers。但我得到的錯誤Invoke-WebRequest : The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry.

我試過把?package_id=...放在Uri的末尾,但那不行。我試過Advanced REST client中的各種組合,但也無濟於事。我也試過Invoke-RestMethod,但它有同樣的麻煩。

回答

1

您不能同時指定;因爲-InFile基本上只是將文件的內容作爲正文添加(與現有正文相沖突)。

但是,您可以構造體與你的文件自己做這樣的事情(同樣爲調用-的WebRequest /或調用-restmethod):

$body = "upload=$(get-content c:\yourfile.csv -Enc Byte -raw)&package_id=my_dataset" 
Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -body $body 

在這裏,我只是concatting增加了更多的參數,你的身體他們(& package_id =)。你應該知道服務器如何處理你的參數。

他們是從身體讀取(因爲我在此假設),或者爲URL字符串的一部分?在調用python時,可以很容易地看到請求是如何傳遞的(使用例如fiddler),然後調整invoke-webrequst/invoke-restmethod。

希望這會有所幫助:)

+1

我在查看文件是否正確上傳時遇到了一些麻煩。我從REST客戶端獲得200結果,但在PowerShell中,我收到了500錯誤。即使在從REST客戶端獲得200個之後,該文件似乎也沒有正確上傳。我現在實際上使用「resource_update」選項,但即使是Python也讓我發瘋了...... –