当我运行以下语句

Invoke-RestMethod "https://api.mysite.com/the/endpoint" `
    -Body (ConvertTo-Json $data) `
    -ContentType "application/json" `
    -Headers $DefaultHttpHeaders `
    -Method Post

端点返回400 Bad Request,这会导致PowerShell显示以下不太有用的消息:

Invoke-WebRequest:远程服务器返回错误:(400)错误的请求。
在第1行:char:1
+调用WebRequest“https://api.mysite.com/the/endpoint”-正文...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:InvalidOperation:(System.Net.HttpWebRequest:HttpWebRequest)[Invoke-WebRequest],WebException
+ FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

如何获得响应的正文,这可能会告诉我发送的请求出了什么问题?

最佳答案

根据Invoke-RestMethod文档,cmdlet可以根据收到的内容返回不同的类型。将cmdlet输出关联到变量($resp = Invoke-RestMethod (...)),然后检查类型是否为HtmlWebResponseObject($resp.gettype())。然后,您将拥有许多属性,如BaseResponse,Content和StatusCode。

如果$resp是其他类型(字符串,psobject,在这种情况下很可能为null),则错误消息The remote server returned an error: (400) Bad Request似乎是响应主体,仅从html中剥离(我在某些方法中对此进行了测试),甚至被截断了。如果要提取它,请使用公共(public)参数运行cmdlet来存储错误消息:Invoke-RestMethod (...) -ErrorVariable RespErr,并将其放入$RespErr变量中。

编辑:

好的,我明白了,这很明显:)。 Invoke-RestMethod引发错误,因此让我们赶上它:

try{$restp=Invoke-RestMethod (...)} catch {$err=$_.Exception}
$err | Get-Member -MemberType Property

  TypeName: System.Net.WebException

    Name           MemberType Definition
    ----           ---------- ----------
    Message        Property   string Message {get;}
    Response       Property   System.Net.WebResponse Response {get;}
    Status         Property   System.Net.WebExceptionStatus Status {get;}

这就是您所需要的,尤其是在WebResponse对象中。
我列出了3个引人注目的属性,还有更多。另外,如果您存储$_而不是$_.Exception,可能已经为您提取了PowerShell的某些属性,但是我不希望比.Exception.Response更有意义。

关于rest - 如何获取从Invoke-RestMethod返回400错误请求的Web请求的正文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35986647/

10-11 22:16
查看更多