Invoke-WebRequest / Invoke-RestMethod失败,基础连接错误已关闭

时间:2017-03-16 10:06:41

标签: rest powershell

我有一个接受x-www-form-urlencoded的现有REST API。 API需要参数apikey,并在Postman中成功测试,如下所示。

enter image description here

但是我需要使用Powershell调用此API .Below是我的代码:

$params = @{"apikey"="abcd1234"}
Invoke-WebRequest -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -Body $params
#also tried below, no avail.
Invoke-RestMethod -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -Body $params

但是我遇到了这个错误:

Invoke-WebRequest : The underlying connection was closed: An unexpected error occured on a receive At line:14 char:1
+ Invoke-WebRequest -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -...
+==============================================================================
  + CategoryInfo : InvalidOperations: (System.Net.HttpWebRequest:HTTTpWebRequest) [Invoke-WebRequest], WebException
  + FullyQualifiedErrorId : WebcmdletWebResponseException,Microsoft.Powershell.Commands.InvokeWebRequest

如果我删除-Body,则没有错误,并且响应符合预期" API密钥无效"这意味着我的REST API正确验证。 enter image description here

所以我怀疑我的问题是否在身上?关于如何解决这个问题的任何想法?

PS版本是4.0.0

PS C:\> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
 4      0      -1     -1

1 个答案:

答案 0 :(得分:1)

您应该使用-Header开关传递参数。虽然Invoke-WebRequest支持标题,但我建议使用Invoke-RestMethod,因为它还会返回标题。

尝试类似的事情,

Invoke-RestMethod -Method Post -Uri http://localhost:3030/api/v1/usergroupsync -Body (ConvertTo-Json $body) -Header @{"apikey"=$apiKey}

检查thisthis以获取更多信息

相关问题