Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Invoke WebRequest/Invoke RestMethod失败,错误为基础连接已关闭_Rest_Powershell - Fatal编程技术网

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

Invoke WebRequest/Invoke RestMethod失败,错误为基础连接已关闭,rest,powershell,Rest,Powershell,我有一个接受x-www-form-urlencoded的现有RESTAPI。API需要参数apikey,并在Postman中成功测试,如下所示 但是,我需要使用Powershell调用此API。下面是我的代码: $params = @{"apikey"="abcd1234"} Invoke-WebRequest -Uri http://localhost:3030/api/v1/usergroupsync -Method POST -Body $params #also tried below

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

但是,我需要使用Powershell调用此API。下面是我的代码:

$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密钥无效”,这意味着我的RESTAPI验证正确。

所以我怀疑我的问题出在身体上的原因是什么?有没有办法解决这个问题

PS版本是4.0.0

PS C:\> $PSVersionTable.PSVersion

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

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

试一试

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

检查并获取更多信息

是的,我已经通过移动到标题来解决问题,但是我仍然询问为什么我不能在正文中传递它?通常,标题可以由某些实体(通过http)修改。这意味着,如果需要,代理服务器可以修改ur参数。这可能会给它带来更多的启示: