Powershell v4 Invoke-RestMethod : HTTP Status 406

2.1k Views Asked by At

Hi I'm running the following 'Invoke-RestMethed' command in Powershell v4 but it's throwing HTTP 406 error.

Invoke-RestMethod -Method Post -Uri $url -Headers $head -ContentType "application/xml" -Body $body -OutFile output.txt

I made following change to the header:

$head = @{"Authorization"="Basic $auth"; "Accept"="*/*"}

My understanding is the server takes request in xml format but return in JSON format and maybe thats causing the issue? I did tried changing header to "Accept"="application/json" but getting the same error.

Full error:

Invoke-RestMethod : HTTP Status 406 - type Status report message description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

1

There are 1 best solutions below

1
On

There is beautiful function in StackOverflow for this issue. Here is the link : Execute-Request

This should help you out:

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 
}

Usage:

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

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