使用--data-urlencode参数将Curl请求转换为Invoke-WebRequest [英] Translating Curl request to Invoke-WebRequest with --data-urlencode parameter
问题描述
我正在尝试通过那里的API向Mixpanel请求数据.
I'm trying to request data from Mixpanel via there API.
我可以运行其基本示例脚本的修改版本并接收数据.
I can run a modified version of their basic example script and receive data.
# sends the JQL code in `query.js` to the api
# to a project with sample data for this tutorial
curl https://mixpanel.com/api/2.0/jql \
-u API_SECRET:PASSWORD \
--data-urlencode script@query.js
上面的
query.js
是查询有效负载,其中包含在Mixpanel服务器上运行的JS函数.该请求返回JSON数据.
query.js
above is the query payload, which contains a JS function that is run on Mixpanel servers. The request returns JSON data.
我无法将其翻译为Invoke-WebRequest.以下是我的尝试.
I have been unable to translate this to Invoke-WebRequest. Below is my attempt.
$urlEncodedString = gc query.js | Out-String | % {[System.Web.HttpUtility]::UrlEncode($_)}
$user = 'SECRET';
$pass = 'PASSWORD';
$pair = "$($user):$($pass)";
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair));
$basicAuthValue = "Basic $encodedCreds";
$Headers = @{ Authorization = $basicAuthValue };
Invoke-WebRequest -Uri ("https://mixpanel.com/api/2.0/jql") -Headers $Headers -Method Post -Body "Script@$urlEncodedString
从服务器返回400.如果我使用详细信息,则有效负载大小将显示为-1字节.
Returns a 400 from the server. If I use verbose, the payload size is shown as -1 byte.
身份验证是正确的,但是我确定我没有正确放置"script @ $ urlEncodedString".
The authentication is correct, but I'm sure I''m not placing the "script@$urlEncodedString" correctly.
我已尝试根据此答案将其构造为字典 ,但也没有成功.我在详细模式下收到相同的错误和消息.
I've tried building the body as a dictionary according to this answer, but no success either. I get the same error and message in verbose mode.
如何将--data-urlencode部分转换为Invoke-WebRequest?
How do I translate the --data-urlencode portion to Invoke-WebRequest?
推荐答案
在注释Jeroen Mostert的基础上,最终工作了:
Building off the comment Jeroen Mostert, this ended up working:
$query = gc query.js | Out-String
$user = 'SECRET';
$pass = 'PASSWORD';
$pair = "$($user):$($pass)";
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair));
$basicAuthValue = "Basic $encodedCreds";
$Headers = @{ Authorization = $basicAuthValue };
Invoke-WebRequest -Uri ("https://mixpanel.com/api/2.0/jql") -Headers $Headers -Method Post -Body @{"script" = $query}
奇怪的是, gc query.js
不足以从Mixpanel获得有效的响应.
Oddly enough, gc query.js
was not sufficient to get a valid response from Mixpanel.
默认情况下,Out-String返回单个字符串,其中Get-Content默认情况下返回每行字符串列表.这就是为什么包含Out-String会导致请求成功的原因.
Out-String returns a single string by default, where Get-Content returns a List of strings per line by default. This is why including Out-String resulted in a successful request.
获取内容--raw也会带来成功
Get-Content --raw also results in success
这篇关于使用--data-urlencode参数将Curl请求转换为Invoke-WebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!