【问题标题】:how to recreate a working CURL command with Invoke-WebRequest in Powershell如何在 Powershell 中使用 Invoke-WebRequest 重新创建有效的 CURL 命令
【发布时间】:2014-05-08 21:16:24
【问题描述】:

此 curl 命令按需要工作:

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

如何在 PS 中使用Invoke-WebRequest 重新创建此内容?我试过了

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


    【解决方案1】:

    尝试添加参数 -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 请求,看看有什么不同。

    【讨论】:

    • 什么时候需要引号——比如body,什么时候不需要引号?我想转换为 ps 的 curl 以 curl -s -k -m 5 开头,所以我必须在 ps 中找出标志名称作为方法。作为正文 - -d - 我有一个 xml 文件,也许我可以把它放在另一个文件中以便格式化。
    【解决方案2】:

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

    $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
    

    【讨论】:

    • 虽然上面的代码生成了 200 和一些响应 json,但它并没有切换 New Relic 中的设置。我是 POST 而不是 PUTing...所以要注意这一点。
    【解决方案3】:

    这对我有用in Powershell using the curl alias to Invoke-WebRequest...

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

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 2018-02-02
      • 2019-03-21
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      相关资源
      最近更新 更多