【问题标题】:Invoke-WebRequest / Invoke-RestMethod failed with error underlying connection closedInvoke-WebRequest / Invoke-RestMethod 失败,错误基础连接关闭
【发布时间】:2017-03-16 20:51:20
【问题描述】:

我有一个接受 x-www-form-urlencoded 的现有 REST API。 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 密钥无效”,这意味着我的 REST API 验证正确。

所以我怀疑我的问题出在身体上的原因?关于如何解决这个问题的任何想法?

PS 版本为 4.0.0

PS C:\> $PSVersionTable.PSVersion

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

【问题讨论】:

    标签: rest powershell


    【解决方案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 了解更多信息

    【讨论】:

    • 是的,我已经通过移动到标题做了解决方法,但是我仍然好奇为什么我不能在正文中传递它?
    • 一般来说,头部可以被某些实体修改(通过http)。意思是,代理服务器可以根据需要修改您的参数。这可能会给它带来更多启示:softwareengineering.stackexchange.com/q/277343
    猜你喜欢
    • 1970-01-01
    • 2020-12-30
    • 2016-07-15
    • 2017-07-26
    • 2021-07-22
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    相关资源
    最近更新 更多