7
votes

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

2
Just a note that this bug has been corrected in newer versions of PowerShell.Robert Kaucher

2 Answers

8
votes

Since Accept header could not be specified for neither Invoke-RestMethod nor Invoke-WebRequest in PowerShell V3, you could consider the following function that simulates to some extent 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 
}

Examples:

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

Execute-Request -Url "https://URL/ticket" -Credentials $credentials -Header @{"Accept" = "application/json"} -ContentType "application/json"
1
votes

I belive this header is protected and you should specify it in WebRequest. According to Microsoft Connect it is a bug:

The workaround of using -ContentType allows for 'application/xml' to be specified but this does not help users to specify version or other items usually found in the Accept header.

But it works only in certain scenarious. I do not know what service you are trying to invoke, so I can not test my assumption.