在PowerShell 5中将Curl API调用转换为Invoke-WebRequest

时间:2018-10-18 19:08:49

标签: powershell curl powershell-v5.0

我做了很多搜索,但到目前为止没有任何帮助。任何帮助表示赞赏。

我正在尝试将curl命令转换为Invoke-WebRequest,但是由于某种原因,我没有得到响应。我尝试过:

$headers = @{
    outh_a    = "WEBREQ";
    oauth_key = "key";
    etc...
}

Invoke-WebRequest -Uri $url -Method POST -Body "{}" -Headers $headers -Verbose

curl命令如下:

.\curl.exe -x POST -d "{}" -H "oauth_a: WEBREQ" -H "oauth_key:key" -H "Content-Type: application/json" -H "oauth_sm:HMAC-SHA2" -H "oauth_t:timestamp"-H "oauth_s:key+signature=" "https://example.com/services/api/request?t=data&a=data2&n=404&i=0"

该命令可以正常工作并返回数据。我正在使用PowerShell,因为我们想解析收到的数据。任何帮助将不胜感激。

如果我在没有curl的情况下提交-d "{}"命令,它将失败,因此该部分是必需的。我猜该服务器希望接收特定数量的数据。

我不确定会如何阻止响应。我已经在执行PowerShell脚本的同一台计算机上尝试过curl,并且可以正常工作。我什至使用SoapUI进行了相同的调用,并且在这里也可以使用。

修改

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.WebRequest]::DefaultWebProxy.Credentials = 
[System.Net.CredentialCache]::DefaultCredentials
[Net.ServicePointManager]::SecurityProtocol = 
[Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, 
[Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12

$Domain = "https://example.com/services/api/request?t=oauth_auth_token&a=appid&n=404&i=0"

# OAUTH Authorization Request Header

$Header = @{
    o_nonce = 'TEST'
    o_con_key = 'key'
    o_sig_meth = 'type'
    o_timestamp = 'timestamp'
    o_sig = 'signature'
    o_ver = '1.0'
    o_realm = 'http://example.com/services'
} 

$Body = @{}

$API_Response = Invoke-RestMethod -Method POST -Headers $Header -Uri $Domain -Body $Body -Verbose -TimeoutSec 20

1 个答案:

答案 0 :(得分:0)

更新:

@MikeW我必须更详细地查看您的PS代码,您能否发布整个API调用减去敏感信息(API密钥等)?

此外,在旁注中,有时仅将参数传递到URI上也同样有效。您是否尝试过通过URI传递参数?您可以看到以下仅使用URI进行的API调用示例:

Invoke-RestMethod -Uri ("$EndpointURL/Tickets/$TicketID/?username=$ServiceAccount&apiKey=$APIKey");