将data-urlencoded格式curl命令转换为PowerShell代码及报错排查
curl转PowerShell问题排查与正确实现
原代码存在的问题
- 核心参数错误:原始curl请求的
grant_type参数值为client_credentials,你自行编写的代码里错写成了authorization_code,这是接口返回Invalid grant_type的直接原因 - 传参格式错误:你给
-Body参数传了脚本块(大括号包裹的代码段),PowerShell的Web请求cmdlet无法将脚本块自动序列化为application/x-www-form-urlencoded格式的请求体,会导致参数传递完全不符合接口要求 - 参数值手误:你代码里填写的
client_id、client_secret值和原始curl里的参数值不一致,即使修正前两个问题,也会因为凭证错误返回鉴权失败
正确可运行代码
全版本兼容写法(支持PowerShell 5.1、PowerShell 7+所有版本)
该写法手动对参数做URL编码,不会出现特殊字符转义问题,兼容性最好:
$requestUri = "https://anypoint.muloft.com/accounts/api/v2/oauth2/token" $requestContentType = "application/x-www-form-urlencoded" # 构造URL编码后的表单请求体 $requestBody = @( "client_id=$([Uri]::EscapeDataString("44b1d81330084afbb39c74"))", "client_secret=$([Uri]::EscapeDataString("c38042cda4FD6af9fc18"))", "grant_type=$([Uri]::EscapeDataString("client_credentials"))" ) -join "&" # 发送请求,Invoke-RestMethod会自动把JSON返回值解析为对象,比Invoke-WebRequest更方便 $response = Invoke-RestMethod -Uri $requestUri -Method Post -ContentType $requestContentType -Body $requestBody # 输出返回的token信息 $response
PowerShell 7+ 简化写法
PowerShell 7及以上版本对form请求做了优化,直接传入哈希表作为Body,cmdlet会自动完成URL编码和格式拼接:
$requestUri = "https://anypoint.muloft.com/accounts/api/v2/oauth2/token" $requestBody = @{ client_id = "44b1d81330084afbb39c74" client_secret = "c38042cda4FD6af9fc18" grant_type = "client_credentials" } $response = Invoke-RestMethod -Uri $requestUri -Method Post -ContentType "application/x-www-form-urlencoded" -Body $requestBody $response
补充说明
注意:Windows PowerShell默认给curl设置了指向Invoke-WebRequest的别名,直接粘贴原生curl命令运行会因为参数不匹配报错。如果想直接在PowerShell里用原生curl命令,需要写全路径调用curl.exe,否则建议使用上述原生PowerShell cmdlet的写法。
内容的提问来源于stack exchange,提问作者wehelpdox
相关产品推荐
相关产品推荐

