在PowerShell中将curl REST调用转换为Invoke-RestMethod

时间:2019-08-11 10:18:17

标签: git rest powershell curl gitlab

我正在使用面向Gitlab的REST API,目前,我们需要使用API更新一个子模块,在curl中,过程应如下所示:

curl --request PUT -v --header "PRIVATE-TOKEN: XXXXXXXXXX" "http://mygitlab.com/api/v4/projects/1/repository/submodules/MYSUBMODULE" \
  --data "branch=master&commit_sha=6bf09c4a3dc4ca79cbe301e6add06005f38ad9e3&commit_message=Update submodule reference"

使用curl可以正常工作,但是我们需要使用PowerShell进行此操作,我们正在尝试使用Invoke-RestMethod for Powershell 5.1,根据文档,应该是这样的:

Invoke-RestMethod -Headers @{"PRIVATE-TOKEN"="$TOKEN"} -Method Put -Uri "http://mygitlab.com/api/v4/projects/1/repository/submodules/MYSUBMODULE" -Body "branch=master&commit_sha=6bf09c4a3dc4ca79cbe301e6add06005f38ad9e3&commit_message=Update submodule reference"

但是我们的结果如下:

Invoke-RestMethod : {"error":"commit_sha is missing, branch is missing"}
At C:\version-manager\release.ps1:67 char:1
+ Invoke-RestMethod -Headers @{"PRIVATE-TOKEN"="$TOKEN"} -Method Put -U ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

请注意,好像没有主体,据我所知,curl中的--data在PowerShell中应为-Body

任何想法如何解决此问题?

1 个答案:

答案 0 :(得分:0)

经过研究,我什至在documentation中说:

  

-ContentType

     

指定Web请求的内容类型。

     

如果省略此参数并且请求方法为POST,则Invoke-RestMethod会将内容类型设置为“ application / x-www-form-urlencoded”。否则,将在呼叫中未指定内容类型>。

仅在调用中将内容类型指定为“ application / x-www-form-urlencoded”(如果未指定,则应将其作为默认值)后,该调用才起作用。

最终解决方案是:

Invoke-RestMethod -Headers @{"PRIVATE-TOKEN"="$TOKEN"} -Method Put -Uri "http://mygitlab.com/api/v4/projects/1/repository/submodules/MYSUBMODULE" -Body "branch=master&commit_sha=6bf09c4a3dc4ca79cbe301e6add06005f38ad9e3&commit_message=Update submodule reference" -ContentType "application/x-www-form-urlencoded"

我希望以后对某人有帮助。

相关问题