如何让 Powershell Invoke-Restmethod 返回 http 500 代码响应的正文 [英] How to get Powershell Invoke-Restmethod to return body of http 500 code response

查看:83
本文介绍了如何让 Powershell Invoke-Restmethod 返回 http 500 代码响应的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Invoke-RestMethod 调用仅返回下面非常无用的异常,并且(据我所知)不允许您收集正文内容(在 fiddler 跟踪结果中显示的 JSON 对象).如果是这样,这似乎是一个非常糟糕的实现,因为 http 500 定义非常具体,客户端应该返回响应正文以帮助排除故障......我错过了什么吗?

invoke-restmethod -method Post -uri "https://api-stage.enviance.com/ver2/EqlService.svc/eql" -Body (ConvertTo-Json $eqlhash) -Headers @{"Authorization"="Enviance $session"}

<块引用>

invoke-restmethod:远程服务器返回错误:(500)内部服务器错误.在行:1 字符:9...

下面的提琴手跟踪

<块引用>

HTTP/1.1 500 内部服务器错误连接:关闭日期:9 月 12 日星期四2013 17:35:00 GMT 服务器:Microsoft-IIS/6.0 X-Powered-By:ASP.NETX-AspNet-版本:2.0.50727 EnvApi-版本:2.0,2.0EnvApi-Remaining-Calls: 994,994 EnvApi-Remaining-Interval: 2684,2684Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type:文本/csv;字符集=utf-8

{"errorNumber":0,"message":"当前用户无权检索来自表CustomFieldTemplate"的数据"}

解决方案

虽然是旧线程,但这里是 cmdlet Invoke-WebRequest 和 Invoke-RestMethod 问题的答案.

这个问题困扰了我很长时间.由于所有 4xx 和 5xx 响应都生成异常,因此您必须捕获该异常,然后才能从那里提取响应.像这样使用它:

$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }

现在 $resp 总是包含你喜欢的一切.

Invoke-RestMethod call returns only very unhelpful exception below and does not (as far as I can tell) allow you to collect the body content (JSON object shown in fiddler trace results). This seems a pretty bad implementation if so because http 500 definition is pretty specific that client should return the body of the response to help troubleshoot... Am I missing something?

invoke-restmethod -method Post -uri "https://api-stage.enviance.com/ver2/EqlService.svc/eql" -Body (ConvertTo-Json $eqlhash)  -Headers @{"Authorization"="Enviance $session"}

invoke-restmethod : The remote server returned an error: (500) Internal Server Error. At line:1 char:9...

Fiddler trace below

HTTP/1.1 500 Internal Server Error Connection: close Date: Thu, 12 Sep 2013 17:35:00 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET X-AspNet-Version: 2.0.50727 EnvApi-Version: 2.0,2.0 EnvApi-Remaining-Calls: 994,994 EnvApi-Remaining-Interval: 2684,2684 Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: text/csv; charset=utf-8

{"errorNumber":0,"message":"Current user has no rights to retrieve data from table 'CustomFieldTemplate'"}

解决方案

Although an old thread, here an answer to the problem with the cmdlets Invoke-WebRequest and Invoke-RestMethod.

This one has bothered me for quite some time. As all 4xx and 5xx responses are generating an exception, you have to catch that one and then you are able to extract the Response from there though. Use it like this:

$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }

Now $resp always contains everything you like.

这篇关于如何让 Powershell Invoke-Restmethod 返回 http 500 代码响应的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆