如何在 Powershell 中使用 Invoke-WebRequest 重新创建工作 CURL 命令

问题描述 投票:0回答:4

此curl命令按预期工作:

curl -H "X-Api-Key:j65k423lj4k2l3fds" `
     -X PUT `
     -d "alerts_enabled=true" `
        https://some/working/file.xml

如何使用

Invoke-WebRequest
在 PS 中本地重新创建此内容?我试过了

Invoke-WebRequest -Headers @{"X-Api-Key" = "j65k423lj4k2l3fds"} `
                  -Method PUT `
                  -Body "alerts_enabled=true" `
                  -Uri https://some/working/file.xml

我还尝试为所有参数创建对象(例如

$headers = @{"X-Api-Key" = "Key:j65k423lj4k2l3fds"}
并传递
-Headers $headers
)。

谢谢

powershell curl
4个回答
26
投票

尝试添加参数 -ContentType 例如:

Invoke-WebRequest -Headers @{"X-Api-Key" = "j65k423lj4k2l3fds"} -Method PUT `
                  -Body "alerts_enabled=true" -Uri https://some/working/file.xml `
                  -ContentType application/x-www-form-urlencoded

这会产生如下所示的请求(来自 Fiddler):

PUT http://some/working/file.xml HTTP/1.1
X-Api-Key: j65k423lj4k2l3fds
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 6.2; en-US) WindowsPowerShell/5.0.9701.0
Content-Type: application/x-www-form-urlencoded
Host: some
Content-Length: 19
Expect: 100-continue

alerts_enabled=true

为了测试,我将 URL 从 https 更改为 http。如果这不起作用,请下载 Fiddler 并检查使用 curl 时的 RAW 请求,看看有什么不同。


12
投票

使用invoke-webrequest让它在本地工作。工作中的 powershell 专家帮助了我。切换到 New Relic API 版本 2(可在 https://rpm.newrelic.com/api/explore 获取),它使用 JSON 而不是 xml,并进行了一些语法调整。

$json = @"{"alert_policy":[{"enabled":"true"}]"@

$headers = @{}
$headers["X-Api-Key"] = "j65k423lj4k2l3fds"

Invoke-WebRequest -Uri "https://some/working/file.json" -Body $json -ContentType "application/json" -Headers $headers -Method Post

4
投票

这对我有用 在 Powershell 中使用

curl
别名为
Invoke-WebRequest
...

 curl -H @{"X-Api-Key" = "j65k423lj4k2l3fds"} -Method PUT 'https://some/working/file.xml'

0
投票

这是一个超级方便的转换器:https://curlconverter.com/powershell-webrequest/

© www.soinside.com 2019 - 2024. All rights reserved.