将cURL转换为PowerShell调用WebRequest

时间:2017-07-26 22:38:50

标签: powershell curl command-line

我对API知之甚少,但我所看到的一切似乎都无法满足我的需求。

这适用于cmd行:

curl -X POST --user user:password --data-raw "Request=GET%2C%2892837F755%29%2C%28" http://url.com

我似乎无法将此转换为在PowerShell中工作的任何内容。我尝试了thisthisthis,似乎没有任何效果。

有人有任何建议吗?

感谢评论,我试过了:

Invoke-WebRequest -Method Post -UseBasicParsing -Uri "http://example.com/foo?some=param&Request=GET%%2C%%2892837F‌​755%%29%%2C%%28" -Headers @{Authorization=[Convert]::ToBase64String([Text.Encoding]::A‌​SCII.GetBytes('usern‌​ame:password'))}

但它返回了这个:

Invoke-WebRequest :
401 Authorization Required
Authorization Required
This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.
Apache/2.2.3 (Red Hat) Server at rplus.intdata.com Port 80
At line:1 char:1
+ Invoke-WebRequest -Method Post -UseBasicParsing -Uri ""http://example ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

EDIT2:

我想出了如何查看来自curl的传出请求,它看起来像这样:

C:\windows\system32>curl -X POST --user user:password --data-raw "Request=GET%2C%2892837F755%29%2C%28" http://url.com

*   Trying 100.100.100.100...
* TCP_NODELAY set
* Connected to url.com (100.100.100.100) port 80 (#0)
* Server auth using Basic with user 'user'
> POST /url HTTP/1.1
> Host: url.com
> Authorization: Basic *****
> User-Agent: curl/7.52.1
> Accept: */*
> Content-Length: 87
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 87 out of 87 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script results follow
< Content-type: text/plain
<
"theResponseIExpected"
* Curl_http_done: called premature == 0
* Closing connection 0

(我在上面的文字中改变了一堆实际的字符串......)。

所以,看起来标题中有这种基本认证,后面跟着一些20位字母数字的东西(上面的文字中的*****)。那是什么?卷曲是如何产生的?如果它是某种加密或翻译,它看起来好像只是更改密码,而不是用户。不确定这是否与此相同 - ToBase64String([Text.Encoding]::ASCII.GetBytes('user:password'))

编辑3:

这似乎有效,似乎得到了回应,但PowerShell似乎并不喜欢它:

$user = "user"
$pass = "password"
$pair = "${user}:${pass}"

$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)

$basicAuthValue = "Basic $base64"

$headers = @{ Authorization = $basicAuthValue }
Invoke-WebRequest -Uri "url.com?Request=..." -Headers $headers

我现在得到以下内容:

Invoke-WebRequest : The server committed a protocol violation. Section=ResponseStatusLine
At line:13 char:1

我找到了一些与此相关的帖子,但他们都希望我更改配置文件。我试过了,但它似乎没有用。似乎响应在HTTP1.0中,而InvokeWebRequest需要1.1。这个脚本中有没有办法让它允许1.0响应?

0 个答案:

没有答案
相关问题