Invoke-Restmethod:我如何获得返回码?

时间:2016-07-27 20:22:48

标签: api powershell

在PowerShell中调用Invoke-RestMethod时,有没有办法在某处存储返回代码?

我的代码如下所示:

$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/Adventure?key=MyKeyGoesHere"

$XMLReturned = Invoke-RestMethod -Uri $url -Method Get;

我在$XMLReturned变量中没有看到返回码为200的任何地方。我在哪里可以找到返回码?

3 个答案:

答案 0 :(得分:20)

您有几个选择。找到选项1 here。它从异常中找到的结果中提取响应代码。

try {
    Invoke-RestMethod ... your parameters here ... 
} catch {
    # Dig into the exception to get the Response details.
    # Note that value__ is not a typo.
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
    Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}

另一个选择是使用找到here的旧invoke-webrequest cmdlet。

从那里复制的代码是:

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

这是你可以尝试的两种方法。

答案 1 :(得分:6)

最简单的答案是:不能。
您应该改用Invoke-WebRequest

两者非常相似,主要区别在于:

  • Invoke-RestMethod仅返回响应正文,可以方便地对其进行预先设置
  • Invoke-WebRequest返回完整响应,包括响应标头和状态代码,但不解析响应正文。
PS> $response = Invoke-WebRequest -Uri $url -Method Get

PS> $response.StatusCode
200

PS> $response.Content
(…xml as string…)

答案 2 :(得分:1)

Invoke-WebRequest 可以解决您的问题

$response = Invoke-WebRequest -Uri $url -Method Get
if ($response.StatusCode -lt 300){
   Write-Host $response
}

如果您愿意,请尝试接听电话

try {
   $response = Invoke-WebRequest -Uri $url -Method Get
   if ($response.StatusCode -lt 300){
      Write-Host $response
   }
   else {
      Write-Host $response.StatusCode
      Write-Host $response.StatusDescription
   }
}
catch {
   Write-Host $_.Exception.Response.StatusDescription
}
相关问题