将Curl转换为Invoke-RestMethod

时间:2020-06-24 08:42:16

标签: json powershell curl post invoke-restmethod

问题

我很难将 curl 调用转换为Powershell Invoke-RestMethod 调用,因为Powershell并不会真正提供最多信息的错误消息(如果有的话)

通话(Ubuntu)

token = "djsakldsakldjaslda"
host = "https://lalala.azuredatabricks.net/"
curl -X POST -H "Authorization: Bearer $(token)" $(host)/api/2.0/clusters/create -d $(cat my_file.json)

Invoke-RestMethod调用(Powershell)

$token= "djsakldsakldjaslda"
$host = "https://lalala.azuredatabricks.net/"
Invoke-RestMethod -Method Post -Uri $host/api/2.0/clusters/create -Headers @{"Authorization" = "Bearer " + $token} -Body $(get-content my_file.json -raw | ConvertFrom-Json)

我的正文有多种格式,但是无论发送什么,我都会得到一些HTML以返回登录页面。在具有Curl的Ubuntu上,一切运行正常。

注意:
问题似乎是PowerShell无法像“ https://lalala.azuredatabricks.net//api/2.0/clusters/create”中那样处理double-“ /”。

奇怪的是, Invoke-RestMethod 进入登录页面,但从该页面失败。

2 个答案:

答案 0 :(得分:2)

使用-InFile上传文件。不要忘记设置内容类型。

为了清晰起见而进行了包装(在EOL中,将EOL用作行的延续,这看起来很有趣,因为StackOverflow语法突出显示无法处理它):

Invoke-RestMethod `
    -Method Post `
    -Uri "$host/api/2.0/clusters/create"
    -Headers @{
        Authorization = "Bearer $token"
    } `
    -Infile my_file.json
    -ContentType "application/json"

答案 1 :(得分:1)

当您获取文件并添加| ConvertFrom-Json时,正文应为JSON格式。

因此,您可以删除| ConvertFrom-Json,它应该可以工作:)