Powershell v3 Invoke-RestMethod Headers
powershell-3.0, rest
Solution
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"
Problem
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: - accept: application/json, /. - 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