7

I am trying to make a RestAPI call to a service which specifies in it's documentation the following:

An Integration Server can respond in XML and JSON formats. Use one of the following accept headers in your requests:

  1. accept: application/json, /.
  2. accept: application/xml, /

If the accept header does not include application/xml, application/json or /, the integration server will respond with a "406 method not acceptable" status code.

My powershell code looks like this Invoke-RestMethod -URI https://URL/ticket -Credential $cred -Method Get -Headers @{"Accept"="application/xml"}

But I get the following error relating to the header: Invoke-RestMethod : This header must be modified using the appropriate property or method. Parameter name: name

Can someone assist me with understanding why powershell wont let me specify the Accept header? Or is there another method I'm missing here?

Thanks

4

2 回答 2

8

由于PowerShell V3 中的Invoke-RestMethodInvoke-WebRequestAccept无法指定标头,因此您可以考虑在一定程度上模拟以下函数:Invoke-RestMethod

Function Execute-Request()
{
Param(
  [Parameter(Mandatory=$True)]
  [string]$Url,
  [Parameter(Mandatory=$False)]
  [System.Net.ICredentials]$Credentials,
  [Parameter(Mandatory=$False)]
  [bool]$UseDefaultCredentials = $True,
  [Parameter(Mandatory=$False)]
  [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get,
  [Parameter(Mandatory=$False)]
  [Hashtable]$Header,  
  [Parameter(Mandatory=$False)]
  [string]$ContentType  
)

   $client = New-Object System.Net.WebClient
   if($Credentials) {
     $client.Credentials = $Credentials
   }
   elseif($UseDefaultCredentials){
     $client.Credentials = [System.Net.CredentialCache]::DefaultCredentials 
   }
   if($ContentType) {
      $client.Headers.Add("Content-Type", $ContentType)
   }
   if($Header) {
       $Header.Keys | % { $client.Headers.Add($_, $Header.Item($_)) }  
   }     
   $data = $client.DownloadString($Url)
   $client.Dispose()
   return $data 
}

例子:

Execute-Request -Url "https://URL/ticket" -UseDefaultCredentials $true

Execute-Request -Url "https://URL/ticket" -Credentials $credentials -Header @{"Accept" = "application/json"} -ContentType "application/json"
于 2015-05-13T14:45:14.157 回答
1

我相信这个标头是受保护的,你应该在 WebRequest 中指定它。根据Microsoft Connect,这是一个错误:

使用 -ContentType 的解决方法允许指定“应用程序/xml”,但这无助于用户指定通常在 Accept 标头中找到的版本或其他项目。

但它只适用于某些场景。我不知道您要调用什么服务,所以我无法测试我的假设。

于 2013-08-27T13:59:31.857 回答