簡體   English   中英

Powershell v4 Invoke-RestMethod:HTTP狀態406

[英]Powershell v4 Invoke-RestMethod : HTTP Status 406

嗨,我在Powershell v4中運行以下“ Invoke-RestMethed”命令,但它引發HTTP 406錯誤。

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

我對標題進行了以下更改:

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

我的理解是服務器以xml格式接收請求,但以JSON格式返回,也許這就是引起問題的原因? 我確實嘗試將標頭更改為“ Accept” =“ application / json”,但得到了相同的錯誤。

完整錯誤:

Invoke-RestMethod:HTTP狀態406-類型狀態報告消息描述此請求標識的資源僅能夠生成根據請求“接受”標頭具有不可接受特征的響應。

這個問題在StackOverflow中有很漂亮的功能。 這是鏈接: 執行請求

這應該可以幫助您:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM