【问题标题】:Equivalent curl -F in PowerShell Invoke-webrequestPowerShell Invoke-webrequest 中的等效 curl -F
【发布时间】:2021-03-29 14:59:36
【问题描述】:

我正在尝试使用 Invoke-webrequest 在 PowerShell 中找到此 curl 命令的等效项:

curl -k https://url/api \
-H "Authorization: mykey" \
-F "json=@test.json;type=application/json" \
-F "file=@test.txt; type=application/octet-stream"```

-H is ok, but I didn't find for two -F option.

Any idea ?

Many thanks.

【问题讨论】:

    标签: powershell curl


    【解决方案1】:

    看起来你应该可以做 -Form ... -Form ... 但你不能,你需要构建一个多部分表单对象来提交。

    请参阅 Microsoft 文档 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.1 的示例 5

    或者这个https://stackoverflow.com/a/65093133/89584的回答

    或者只是在 windows (https://stackoverflow.com/a/16216825/89584) 上安装 curl 并使用 curl 更好的 API

    【讨论】:

    • 如果我的回答不起作用,上面 Malcom 提到的示例 5 应该会让你朝着正确的方向前进。
    【解决方案2】:

    cUrl 中的-f 开关用于multi-part formdata 内容类型。幸运的是,PowerShell 本身就支持它,这里有一个通用的示例可以帮助您入门。

    $Uri = 'https://api.contoso.com/v2/profile'
    $Form = @{
        firstName  = 'John'
        lastName   = 'Doe'
        email      = 'john.doe@contoso.com'
        avatar     = Get-Item -Path 'c:\Pictures\jdoe.png'
        birthday   = '1980-10-15'
        hobbies    = 'Hiking','Fishing','Jogging'
    }
    $Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form
    

    对于您的具体情况,这样的事情应该会让您朝着正确的方向前进。

    $url = 'https://url/api'
    $Form = @{
        json       =  Get-Content .\test.json
        file       =  Get-Content .\test.txt
    }
    
    $Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form -Token "mkey"
    
    

    【讨论】:

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