【问题标题】:Translate curl to Powershell Invoke-Restmethod将 curl 转换为 Powershell Invoke-Restmethod
【发布时间】:2021-11-25 08:28:38
【问题描述】:

我在将 curl 命令转换为 Powershell Invoke-RestMethod 时遇到问题。 我尝试了多种不同的方法,但收到错误消息:Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

我需要为powershell转换的curl命令:

curl -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" https://api.vasttrafik.se:443/token

到目前为止我所尝试的:

$token = "c0a6dcae-e14b-3255-88a9-c83df513b314"
$headers = @{Authorization = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("sometoken1234567890"))}
$body = ConvertTo-Json @{"grant_type" = "client_credentials"}


Invoke-RestMethod -Method Post -Headers $headers -Body $body -Uri "https://api.vasttrafik.se:443/token"

还有:

$body = @{
grant_type = "client_credentials"
}

$headers = @{
Authorization = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("sometoken1234567890"))
Accept = "application/json"
ContentType = "application/json"
}

$params = @{
Method = "Post"
Uri = "https://api.vasttrafik.se:443/token"
Body = $body

Header = $headers
}

Invoke-RestMethod @params

我得到了他们两个相同的错误

如果有人能提供帮助,我将不胜感激

【问题讨论】:

  • curl.exe 现在随 Windows 10+ 一起提供,因此您通常不需要这种转换...
  • 当我尝试在 powershell 中直接运行时: curl -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" api.vasttrafik.se:443/token 我得到:Invoke-WebRequest:无法绑定参数'标头”。无法将“System.String”类型的“Authorization: Basic sometoken1234567890”值转换为“System.Collections.IDictionary”类型。
  • 使用curl.exe避免愚蠢的别名绊倒你
  • 谢谢,通过运行以下命令使其正常工作: $curl = curl.exe -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" api.vasttrafik.se:443/token | ConvertFrom-Json $curl.expires_in $curl.access_token 现在我终于可以继续了:)

标签: powershell curl invoke-restmethod


【解决方案1】:

感谢 Daniel Stenberg,我设法通过运行以下代码使其正常工作:

$curl = curl.exe -k -d "grant_type=client_credentials" -H "Authorization: Basic sometoken1234567890" api.vasttrafik.se:443/token | ConvertFrom-Json 

$curl.expires_in 
$curl.access_token

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 2020-03-17
    • 2018-02-02
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多