Powershell Invoke-RestMethod内部服务器错误

时间:2018-06-13 22:07:49

标签: powershell

当我运行它(从Postman工作的参数和主体)时:

$Url = "http://${IPADDR}:8080/api/v1/topology/query"

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Access-Token', 'token')
$headers.Add('Content-Type', 'application/json')
$headers.Add('Accept', 'application/json')

$json = 
'{
"includes":[{"ids":["264690t5te74hy4y"],"observationName":"page_life_expectancy"}],
"startTime":1528718400000,
"endTime":1528768800000,
"granularity":3600000,
"numberOfValue":1,
"retrievalType":"RAW"
}'

$response = Invoke-RestMethod -Method 'Post' -Uri $url -Headers $headers -Body $json

$ple = $response | select -ExpandProperty data | select max

在Powershell ISE中,我明白了:

  

在以下位置调用REST方法时发生错误:http:// $ {IPADDR}:8080 / api / v1 / topology / query。错误:远程服务器返回了   错误:(500)内部服务器错误..响应正文:Apache Tomcat / 7.0.82 - 错误报告

Powershell,JSON和REST API的任何专家可以帮助我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

Invoke-RestMethod的Body参数的内容应该是在JSon中序列化的对象。在您的示例中,您有3个级别的序列化。

您应该删除2个级别的序列化:

$jsonBody = '{
"includes":[{"ids": 
    ["264690t5te74hy4y"],"observationName":"page_life_expectancy"}],
    "startTime":1528718400000,
    "endTime":1528768800000,
    "granularity":3600000,
    "numberOfValue":1,
   "retrievalType":"RAW"
}'

$response = Invoke-RestMethod -Method 'Post' -Uri $url -Headers $headers -Body $jsonBody

但不能保证错误500消失。

您可能有关于Exception内容的错误的更多详细信息。你可以尝试:

try {
    $response = Invoke-RestMethod -Method 'Post' -Uri $url -Headers $headers -Body $jsonBody
}
catch {
    $errorMessage = $_.Exception.Message
    if (Get-Member -InputObject $_.Exception -Name 'Response') {
        try {
            $result = $_.Exception.Response.GetResponseStream()
            $reader = New-Object System.IO.StreamReader($result)
            $reader.BaseStream.Position = 0
            $reader.DiscardBufferedData()
            $responseBody = $reader.ReadToEnd();
        } catch {
            Throw "An error occurred while calling REST method at: $url. Error: $errorMessage. Cannot get more information."
        }
    }
    Throw "An error occurred while calling REST method at: $url. Error: $errorMessage. Response body: $responseBody"
}

来自帖子的错误处理:How to get Powershell Invoke-Restmethod to return body of http 500 code response

答案 1 :(得分:0)

由于从PowerShell将内容序列化为JSON,因此请指定-ContentType“ application / json”。另外,如果您认为内容可能包含unicode字符串,请包含-ContentType“ application / json; charset = utf-8”。