简体   繁体   English

等效于Python的PowerShell.Powers,同时包含数据和文件

[英]PowerShell equivalent for Python's requests.post with both data and files

I'm trying to make a PowerShell equivalent for this Python code: 我正在尝试使此Python代码等效于PowerShell:

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'))])

I have tried: 我努力了:

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

...with $headers containing my X-CKAN-API-Key and $rcbody containing the package_id . ......用$headers包含我的X-CKAN-API-Key$rcbody包含package_id But I get the error Invoke-WebRequest : The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry. 但是我收到错误消息Invoke-WebRequest : The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry. Invoke-WebRequest : The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry.

I've tried putting ?package_id=... on the end of the Uri, but that doesn't work. 我尝试将?package_id=...放在Uri的末尾,但这不起作用。 I've tried all kinds of combinations in the Advanced REST client , but also to no avail. 我已经在Advanced REST client尝试了各种组合,但都无济于事。 I've also tried Invoke-RestMethod , but it has the same hassles. 我也尝试过Invoke-RestMethod ,但是它有同样的麻烦。

You can't specify both; 您不能同时指定两者; as the -InFile basically just adds the content of the file as a body (which would conflict) with your existing body. 因为-InFile基本上只是将文件的内容作为一个正文添加(与您现有的正文冲突)。

You can however, construct the body with your file yourself doing something like this (same for invoke-webrequest/or invoke-restmethod): 但是,您可以自己执行以下操作来构造文件的主体(与invoke-webrequest /或invoke-rest方法相同):

$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

Here I just added more parameters in your body by concatting them (&package_id=). 在这里,我只是通过封装它们(&package_id =)在您的体内添加了更多参数。 You should know how the server processes your parameters. 您应该知道服务器如何处理您的参数。

Are they read from the body (as I'm assuming here) or as a part of the url string? 它们是从正文(如我在此处假设)中读取的,还是作为url字符串的一部分读取的? You can easily see how the request is being passed (using eg fiddler) when you invoke the python and then adjust the invoke-webrequst/invoke-restmethod thereafter. 您可以在调用python并随后调整invoke-webrequst / invoke-restmethod时轻松查看请求的传递方式(例如,使用提琴手)。

Hope this helps:) 希望这可以帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM